7
votes

I am trying to make a middleware for different type of users in my Laravel 5.2 app. So, what is I am doing is making different middlewares for different users.

As far as I am knowing Auth::check() will not work without musing middleware web from here.

So, what I have done is-

routes.php

Route::group(['middleware' => ['web','admin']], function ()
{
    //suspend, activate, delete
    Route::get('users', [
        'uses'          => 'AdminController@users',
        'as'            => 'users'
    ]);

    //Edit,activate,suspend, delete
    Route::get('articles', [
        'uses'          => 'AdminController@articles',
        'as'            => 'articles'
    ]);
});

AdminMiddleware.php

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check())
        {
            return "asd";
            //return Auth::user();
            //return redirect('home');
        }
        else
        {
            return redirect('login');
        }

        //now return the valid request
        return $next($request);
    }
}

Kernel.php

protected $routeMiddleware = [
    'auth'          => \App\Http\Middleware\Authenticate::class,
    'admin'         => \App\Http\Middleware\AdminMiddleware::class,
    'user'          => \App\Http\Middleware\UserMiddleware::class,
    'auth.basic'    => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest'         => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle'      => \Illuminate\Routing\Middleware\ThrottleRequests::class,
];

AdminController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class AdminController extends Controller
{
    public function users()
    {
        return view('admin.users');
    }

    public function articles()
    {
        return view('admin.articles');
    }
}

But I am getting this error-

enter image description here

when "return Auth::user();" called inside middleware, "return Auth::user();" is working in other place (view and controllers) but not working like old versions of Laravel.

Can anyone please help?

4
why are you trying to return the user model from a middleware ?lagbox
Actually I want to know user type in my middleware so that I can decide anything to do with that, so as for testing I am trying to return everything.Abrar Jahin
just dd what you want to check, dont return them. What are you trying to check on the 'user' model ?lagbox
user_type - in user modelAbrar Jahin
Actually the problem is not what I am returning, problem is I am not allowed to do Auth::check()Abrar Jahin

4 Answers

4
votes

You could potentially do something like this, adjust where needed

public function handle($request, Closure $next)
{
    $user = $request->user();

    if (! $user || $user->user_type != 'admin') {
        return redirect('login');
    }

    return $next($request);
}

The error you are receiving is coming from the fact that you are not returning a Response object from your middleware. The VerifyCsrfToken middleware is trying to add a cookie to the response it gets from passing the request down the pipeline. In this case it is not getting a Response object but instead a string or User because a string or User was returned in your middleware.

2
votes

Hi @Cowboy and @lagbox , Thanks for trying to help, unfortunately they were not working, but I have solved it.

I have solved it by running-

php artisan cache:clear

composer dump-autoload

php artisan clear-compiled

php artisan optimize

and then middleware-

<?php

namespace App\Http\Middleware;

use Closure;
use Auth;

class AdminMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (Auth::check())
        {
            if(strcmp( "admin" , Auth::user()->user_type ) != 0 )
                return redirect('home');
            else
                return $next($request);
        }
        else
        {
            return redirect('login');
        }

        //now return the valid request
        //return $next($request);
    }
}

And Route-

Route::group(['middleware' => ['web','admin']], function ()
{
    //suspend, activate, delete
    Route::get('users', [
        'uses'          => 'AdminController@users',
        'as'            => 'users'
    ]);

    //Edit,activate,suspend, delete
    Route::get('articles', [
        'uses'          => 'AdminController@articles',
        'as'            => 'articles'
    ]);
});
0
votes

You have added routes in web group as well so make sure your kernel file should have following middleware group.

/**
 * The application's route middleware groups.
 *
 * @var array
 */
protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
    ],

    'api' => [
        'throttle:60,1',
    ],
];

The error due to session. make sure your kernel file contains session middlewares.

-1
votes

I've the same issue. In my case, I'm facing this in Multiple authentication. If you're using Multiple authentications or even single authentication with different primary key name in the table instead of id, This may cause.

In Laravel, the default primary key for the users table is id. In case, you've changed that into user_id or something, You have to mention that in your Model. If not, Laravel can't create the session for the user as a result, the Auth::attempt() will work fine but Auth::check() will not. So, Make sure you've mentioned that inside the model class.

class User extends Authenticatable {
   $primaryKey = 'user_id';