Search code examples
laravelmodelwhere-clauselaravel-8eloquent-relationship

Laravel 8 - How to use where conditions for relation's column


hello friends can you help me to get the contents of $filter? I want to run where which is where the target column is in the relation array

    $filter = $request->get('Biogear');
    $data = DetailBarang::with(['barang' => function ($q) use ($filter) {
        $q->where('brand', '=', $filter);
    }])->get();
    return response()->json($data);

Solution

  • you can try this

        $filter = $request->get('Biogear');
        $data = DetailBarang::with('barang')->whereHas('barang',function (Illuminate\Database\Eloquent\Builder $q) use ($filter) {
            $q->where('brand', '=', $filter);
        })->get();
    
        return response()->json($data);