Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.2 : Undefined Variable in WhereHas

Tags:

laravel

I get undefined variable $jenis_mobil exactly on $q->where('name', $jenis_mobil->name)

    $jenis_mobil = Car_class::find($request->jenis_mobil);
    $dari_kota = City::find($request->dari_kota);       

    $vehicles = Vehicle::whereHas('car', function($q){
        $q->whereHas('car_class', function($q){
            $q->where('name', $jenis_mobil->name);
        });
    })
    ->whereHas('partner', function($q) {
        $q->whereHas('kota_pool', function($q){
            $q->where('name', $dari_kota->name);
        });
    })
    ->where('year', $request->tahun_mobil)
    ->get();

Is something wrong with my code? I think because $jenis_mobil not passed to whereHas

like image 858
Dark Cyber Avatar asked Nov 06 '16 05:11

Dark Cyber


1 Answers

You should use use() to pass variables into the closures:

$vehicles = Vehicle::whereHas('car', function($q) use($jenis_mobil) {
    $q->whereHas('car_class', function($q) use($jenis_mobil) {
        $q->where('name', $jenis_mobil->name);
    });
})
->whereHas('partner', function($q) use ($dari_kota) {
    $q->whereHas('kota_pool', function($q) use ($dari_kota) {
        $q->where('name', $dari_kota->name);
    });
})
->where('year', $request->tahun_mobil)
->get();
like image 86
Alexey Mezenin Avatar answered Oct 13 '22 01:10

Alexey Mezenin