Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel constructor redirect

I have a method for checking if a user's role is an admin, if not, redirect them with return redirect('/')->send();. How can I check for user role and redirect the user without displaying the page and waiting for a redirect?

My Controller:

class AdminController extends Controller
{
    public function __construct()
    {
        if (Auth::check())
        {
            $user = Auth::user();
            if ($user->role != 'admin')
            {
                return redirect('/')->send();
            }
        }
        else
        {
            return redirect('/')->send();
        }
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return View('admin/index');
    }
}
like image 562
lock Avatar asked Jul 03 '16 14:07

lock


People also ask

How do I redirect from one page to another in laravel?

By default laravel will redirect a user to the home page like so: protected $redirectTo = '/home'; To change that default behaviour, add the following code in App/Http/Controllers/Auth/LoginController. php . This will redirect users (after login) to where ever you want.

How do I redirect back in laravel?

If you just want to redirect a user back to the previous page (the most common example - is to redirect back to the form page after data validation failed), you can use this: return redirect()->back();

What is redirect in laravel?

Redirect responses are instances of the Illuminate\Http\RedirectResponse class, and contain the proper headers needed to redirect the user to another URL. There are several ways to generate a RedirectResponse instance. The simplest method is to use the global redirect helper: Route::get('/dashboard', function () {

How do I redirect back to original URL after successful login in laravel?

You may use Redirect::intended function. It will redirect the user to the URL they were trying to access before being caught by the authenticaton filter. A fallback URI may be given to this method in case the intended destinaton is not available.


1 Answers

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');
like image 70
Brotzka Avatar answered Oct 25 '22 13:10

Brotzka