Reputation: 402
I am going to filter data with districtname in my vehicles table like this,
public function index()
{
$vehicles = Vehicle::with('uploads')
->when($request->district, function ($query, $request) {
return $query->where('districtname', $request->district);
})->get();
return view('vehicles.index')->withVehicles($vehicles);
}
and my vehicle table like this,
id districtname vehiclename
1 alabama toyota
2 alamaba ford
3 miyuri bmw
4 misisipi benz
5 miyuri ford
6 alabama toyota
and routes is like this,
Route::get('district', [
'uses' => 'VehicleController@index',
'as' => 'districts.index',
]);
but got following error msg,
Undefined variable: request
in VehicleController.php line 39
how can fix this???
Upvotes: 0
Views: 1349
Reputation: 177
The error
Undefined variable: request
in VehicleController.php line 39
Is because of not using REQUEST in the function index
You will have to use Illuminate\Http\Request in your class as well as you will need to pass the REQUEST obj in your index function.
Check the below code to use it.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SomeController extends Controller
{
public function index(Request $request)
{
$vehicles = Vehicle::with('uploads')
->when($request->district, function ($query, $district) {
return $query->where('districtname', $district);
})->get();
return view('vehicles.index')->withVehicles($vehicles);
}
}
Upvotes: 0
Reputation: 40919
When you call when() on the query builder, the first argument is the value you want to pass to the callback, that is passed as the second argument.
When you do
->when($request->district, function ($query, $request) {
return $query->where('districtname', $request->district);
})
then $request->district is passed to the callback, provided it has a value, therefore there is no need to try to access its district property.
To fix that, change the above to:
->when($request->district, function ($query, $district) {
return $query->where('districtname', $district);
})
Upvotes: 1