laravel constructor redirect
Create your own Middleware. Here is an example. In my example, I have several usergroups in a separate model. You have to change the code for your needs.
Create the Middleware via terminal/console:
php artisan make:middleware UserGroupMiddleware
The created middleware class could be find in app/Http/Middleware/UserGroupMiddleware.php
You need the following code in your middleware:
namespace App\Http\Middleware;
use Closure;
use App\User;
use App\Usergroup;
class UserGroupMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, $group)
{
if($request->user() !== NULL){
$userGroupId = $request->user()->group;
$userGroup = Usergroup::find($userGroupId);
if($userGroup->slug === $group){
return $next($request);
}
}
// Redirect the user to the loginpage
return redirect('/login');
}
}
Now you have to register this middleware in app/Http/Kernel.php
:
protected $routeMiddleware = [
// other middlewares
// Custom Middleware
'group' => \App\Http\Middleware\UserGroupMiddleware::class
];
Finally you need to attach the middleware to your route:
Route::group(['middleware' => 'group:admin'], function(){
// Routes for admins, e.g.
Route::get('/dashboard', 'SomeController@dashboard');
});
// Or for a single route:
Route::get('/dashboard', ['middleware' => 'group:admin'], function(){
return view('adminbereich.dashboard');
});
Remember, that you could pass in multiple middlewares with:
Route::get('/some/route', ['middleware' => ['group:admin', 'auth']], 'SomeController@methodXYZ');