Laravel eloquent call realtionship based on a boolean parameter - laravel

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

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();

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

How To Pass Parameters In String Array Of Functions In With() Laravel

I Try To Pass Parameter To With() Function For Model:
Model::with(['functionA($parameters)', 'functionB'])
I think you are looking for this type.
Model::with(['functionA' => function($query) use ($parameters) {
$query->where('some_column', $parameters);
}, 'functionB'])->get();
Unfortunately, you can't use 'with' for normal function, it's used for eloquent's relationships.
for your case you can proceed like this:
$model = new Model(); // or $model = Model::where(anyConditionYouWant)->first();
$model->functionA($parameters);
you can use your functions any time you want without declare them in 'with' sentence

How to write a query conditionally in laravel?

I am new to the laravel, i am joining three tables based on conditions every thing is working fine but i need to write conditionally if the $field is array it should run with whereIn otherwise it should run where condition,can you please help me to acheive this thing
//$field sometimes it's an array sometimes it's a string.
public function find($field){
}
For conditional constraints, you can use the when() clause:
$query = DB::table(...);
$data = $query
->when(is_array($field), function ($query) use ($field) {
$query->whereIn('my_field', $field);
}, function ($query) use ($field) {
$query->where('my_field', $field);
})
->get();
Now, as a tip, you could do this: Wrap the $fields variables to an array and then use always the whereIn clause. You can achieve this with the Arr::wrap() function:
use Illuminate\Support\Arr;
// ...
$query = DB::table(...);
$data = $query
->whereIn('my_field', Arr::wrap($field))
->get();
PS: I have linked the relevant functions to the docs so you can know how they work and their params.

How can I get a query with a conditional in a third relation?

Im using Laravel 7 and to get an array like this Array image spect result
And im working with Eloquent. This is my code for that array
**return EvaluateTeacherQuestion::with('evaluate_teacher_possibles_answers')->get();**
And this is my function evaluate_teacher_possibles_answers to make the relationship
public function evaluate_teacher_possibles_answers()
{
return $this->hasMany(EvaluateTeacherPossibilites::class)->withCount('evaluate_teacher_answers')->with('evaluate_teacher_answers');
}
And to get the third condition use this
public function evaluate_teacher_answers()
{
return $this->hasMany(EvaluateTeacherAnswer::class, 'evaluate_teacher_possible_id');
}
The problem is in the table evaluate_teacher_answers, I need get only this that if a condition (teacher_id = $teacher) is right.
When you add the whereHas condition a subquery is added.
Eg:
EvaluateTeacherQuestion::with('evaluate_teacher_possibles_answers')->whereHas('evaluate_teacher_possibles_answers',function($query){
$query->where('column','operation','value');
})->get();
With this way, will included relation in model and will execute conditions on closure from related model
Try this way:
remove with('evaluate_teacher_answers') from evaluate_teacher_possibles_answers relation:
public function evaluate_teacher_possibles_answers()
{
return $this->hasMany(EvaluateTeacherPossibilities::class)->withCount('evaluate_teacher_answers')->;
}
then load that relation with your condition:
$value = EvaluateTeacherQuestion::with(['evaluate_teacher_possibles_answers'=>function($query)use($teacher_id)
{
$query->with(['evaluate_teacher_answers'=>function($query)use($teacher_id){
$query = $query->where('evaluate_teacher_answers.teacher_id',$teacher_id);
}]);
}])->get();

Filter based on collection or sub-attribute

My user model has a 'prevregistration' attribute
public function prevregistration()
{
return $this->hasMany(Prevregistration::class, 'prevregistration_userid');
}
My prevregistraton model has a 'prev' attribute
public function prev()
{
return $this->hasOne(Prev::class,'prev_id', 'prevregistration_previd');
}
In my controller I show prevregistrations for the current user:
mynextprevs = Auth::user()->prevregistration ;
Now I want to only show prevregistrations from which the connected prev its prev_date in the future, like this:
$mynextprevs = Auth::user()->prevregistration::whereDate('prev_date', '>=', Carbon::today()->toDateString());
But then I get:
BadMethodCallException
Method Illuminate\Database\Eloquent\Collection::whereDate does not exist.
I also tried like this:
$mynextprevs = Auth::user()->prevregistration->prev::whereDate('prev_date', '>=', Carbon::today()->toDateString());
But then I get:
Property [prev] does not exist on this collection instance.
Should I/how can I filter the collection? I'm curious why Auth::user()->prevregistration->prev is not working, since that are attributes.
Thanks
You need to use the condition whereHas on your prevregistration
$mynextprevs = Auth::user()->prevregistration()->whereHas('prev',function($prev) {
$prev->whereDate('prev_date', '>=', Carbon::today()->toDateString());
})->get();
Notice we used the relation as a method prevregistration() to access it as a query builder and not as a collection hence the need for the ->get() at the end.

Laravel filter using conditions

I have a eloquent model called product. I need to use where condition depends on the status of column in same table. This is my code
public function product_list(Request $request,Datatables $datatables){
$product = Product::where('supplier_id',$request->supplier_id)->where('product','!=',3);
return $datatables->eloquent($product)->filter(function ($query) use ($request) {
if($query->is_from_portalsite==1){
$query->where('status','>',1);
}
})->make(true);
}
I need to check the where condition if the column is_from_portalsite equals to 1. how can I check that in laravel.
Try this (assuming is_from_portalsite is boolean):
$query->where('is_from_portalsite',0)->orWhere('status','>',1);

Resources