Friaku
3 years ago

Middleware & Commas - 5.2

Posted 3 years ago by Friaku

So I'm having a few issues with passing more than parameter to a middleware. It's only accepting the first parameter and the ones that come after.

I'd like to also point out that I've registered the middleware in the kernel. For example:


<?php
Route::group(['middleware' => 'roles:Admin,Author,User'], function()
{
  Route::resource('posts', 'PostsController');
});

It will accept the "Admin" but not the ones after (Author, User). If I were to however place Author in front, then it would accept Author.

CheckRoles.php - Middleware

namespace App\Http\Middleware;

use Closure;
use Auth;

class CheckRoles
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next, $role)
    {

        if(Auth::user()->hasRole($role)){
            return $next($request);
        }
        else
        {
            return response('Insufficient Access', 404);
        }
    }
}

routes.php

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::auth();

Route::get('/home', '[email protected]');


Route::group(['middleware' => 'roles:Admin,Author,User'], function()
{
  Route::resource('posts', 'PostsController');
});

User.php - Model

<?php
//Checks for a specific role
    public function hasRole($role)
    {
        if(is_string($role))
        {
            return $this->roles->contains('name', $role);
        }

        return !! $role->intersect($this->roles)->count();
    }

PostsController - I also tried using the middleware within the controller and commented out the middelware stuff in the routes.php but that didn't work either:


<?php

namespace App\Http\Controllers;

use Gate;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\PostRequest;

use App\Posts;
class PostsController extends Controller
{

    public function __construct()
    {  
        //I tried the below to no avail
        $this->middleware('roles:Admin,Author,User');
    }

    public function show($id)
    {
        $post = Posts::findOrFail($id);
        return view('posts.show', compact('post'));
    }

    public function edit(PostRequest $request)
    {
        return view('posts.edit');
    }

}

Do you guys/ girls have an idea?

Thank you

Please sign in or create an account to participate in this conversation.