简体   繁体   中英

Using variable in where clause

Right now I have this defined in app/routes.php :

View::share('user_image_count', Items::where('user_id', '=', 1)->count());

It returns the number 9 , just what I want.

I would like to make this dynamic so it is based on the user_id of the user that is logged in/authenticated.

I currently use this in my views:

{{ Auth::user()->user_id }}

How can I adjust my query in routes.php so that it uses the authenticated user's id number?

Have you tried with the following?

if (Auth::check())
{
    $user_id     = Auth::user()->user_id;
    $items_count = Items::where('user_id', '=', $user_id)->count();

    View::share('user_image_count', $items_count);
}

I believe it should work.

You may try something like this:

View::share('user_image_count', function(){
    return Auth::check() ? 
           Items::where('user_id', '=', Auth::user()->user_id)->count() : '';
});

In your view:

{{ $user_image_count() }}

I think you can better do this with an helper class .

let's say helper as class

 class Helper{
   public static function GetUserCount($user_id){

       return View::share('user_image_count', Items::where('user_id',$user_id)->count());

   }

}

and in you view call this class and pass user_id to it

Echo this in view {{Helpers::GetUserCount(Auth::user()->user_id)}}

So this way it would be dynamic for all logined user

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM