Home > Blockchain >  Laravel eloquent call realtionship based on a boolean parameter
Laravel eloquent call realtionship based on a boolean parameter

Time:11-25

I'm trying to make a method to retrieve model with a relationship I'd like to be able to fetch the relation based on a boolean parameter for example, I can do it using the if condition like the following

if($load == true){
   $users = User::with('login')->all()->paginate();
}else{
$users = User::all()->paginate();
}

I'm wondering if there's a way to do it without the if condition on the fly

CodePudding user response:

You can use the when() method on the query builder. Note that you don't need to use the all() method when you want to use a paginator.

User::query()
    ->when($load, fn($query) => $query->with('login'))
    ->paginate();

CodePudding user response:

you can use when method:

 $users = User::when($load, function ($query) {
                    return $query->with('login');
                })->paginate(10);

The when method only executes the given closure when the first argument is true. If the first argument is false, the closure will not be executed

  • Related