I'd like to set a default route prefix for all my routes based on the users company e.g.
Route::group(['prefix' => '/{company}'], function() {
Route::get('/', 'CompaniesController@index')->name('company.index');
});
Is there some way i can set this value through middleware etc so i don't have to do something like this on every method and the user only has access to their own company.
public function index(Company $company)
{
if(auth()->user()->company == $company) {
return $company;
}
abort(404);
}
Using Laravel 6.x
You don't need any custom middleware for this you can achieve this with Policies & the build-in can
middleware of laravel.
In your case it will be something like the following:
// app/Policies/CompanyPolicy.php
class PostPolicy
{
public function view(User $user, Company $company)
{
return $user->company->getKey() === $company->getKey();
}
}
// web.php
Route::group(['prefix' => '/{company}'], function() {
Route::get('/', 'CompaniesController@index')->name('company.index');
})->middleware('can:view,company');
// Controller
public function index(Company $company)
{
return 'magic';
}
For more information about this you can watch the following documentation:
https://laravel.com/docs/6.x/authorization#creating-policies
https://laravel.com/docs/6.x/authorization#via-middleware