Friday, March 10, 2017

Laravel : Bind only primary entities to my session

Using Laravel 5.4

I have following entities in my app:

Employees, Contractors, Clients.

I have restfull routes for each like so:

/employees/1
/contractors/1
/clients/1
..

I have the need to get the current entity based on the routes, so i did the following in my RouteServiceProvider:

Route::bind('employee', function ($value) {
    $employee = Employee::findOrFail($value);
    session(['activeEntity' => $employee]);
    return $employee;
});

Route::bind('client', function ($value) {
    $client = Client::findOrFail($value);
    session(['activeEntity' => $client]);
    return $client;
});

Route::bind('contractor', function ($value) {
    $contractor = Contractor::findOrFail($value);
    session(['activeEntity' => $contractor]);
    return $contractor;
});

This works fine for all the top-level routes. But i also have following routes:

/clients/1/employees/1

in this case i would like the activeEntity to be Client, but currently the active entity in the session will be set to Employee

How would i prevent that from happening? And bind the correct entity to the session ?



via Christophvh

Advertisement