0

I got table called Vehicles in whose model Vehicle are defined two relationships.

public function type(){
        return $this->belongsTo("App\VehiclePivot", 'vehicle_type_id', "id");
    }

and

public function workOrganization(){
        return $this->belongsTo("App\WorkOrganization", 'workOrganization_id', "id");
    }

When used as

$vehicles = Vehicle::with("type", "workOrganization");

they work great. Show for every vehicle their type and their work organization.

If i try

$vehicles = Vehicle::whereHas("type", function($query) use($request){
                            $query->where('name', '=', $request->type);
                        })->with("type")->get();

or

$vehicles = Vehicle::whereHas("workOrganization", function($query) use($request){
                            $query->where('name', '=', $request->workOrg);
                        })->with("workOrganization")->get();

They also work.

User can enter type or workOrganization, or both or neither of them.

If one is present, then only that relationship should "execute", if both, then both relationship should, also if it neither of them, then also both should execute.

Can it be done via eloquent?

1 Answers1

1

I think you can use when

$vehicles = Vehicle::when(!empty($request->workOrg),function ($query) use($request){
        $query->whereHas("workOrganization", function($query) use($request){
            $query->where('name', '=', $request->workOrg);
        });
    })->when(!empty($request->type),function ($query) use($request){
        $query->whereHas("type", function($query) use($request){
            $query->where('name', '=', $request->type);
        });
    })
        ->with("workOrganization","type")
        ->get();
John Lobo
  • 14,355
  • 2
  • 10
  • 20
  • 1
    Thanks dude. I tried different eloquent combos that i knew before(shown code included), but i guess when explained in plain words works better than pasting all the code that i tried. – Veljko Stefanovic Jul 10 '21 at 14:49
  • I don't want to look "greedy", but do you know by any chance When i search WorkOrganizations for available vehicles, how can i get type of said vehicles? I already done it with two nested for loops and condition where i compare id of passed `$request->type` variable. Is there eloquent way and if so, what's also relationship for WorkOrganizations model that'll "connect" to VehiclePivot via Vehicle model? – Veljko Stefanovic Jul 10 '21 at 17:10
  • @VeljkoStefanovic belongstomany relationship you have to use if its pivot table – John Lobo Jul 10 '21 at 17:14
  • 1
    Solved it with: https://stackoverflow.com/questions/18963483/retrieving-relationships-of-relationships-using-eloquent-in-laravel – Veljko Stefanovic Jul 10 '21 at 19:50