Hareth Shehada
Hareth Shehada

Reputation: 3

How to use a function from helper in routes?

I have a function in helpers.php, which I use in any blade to check if the admin has permission to view some buttons, and it also works in Controllers, but it's not working in routes, the routes ignoring it.

function can($permission)
{
    $userCheck = auth()->guard('admin')->check();
    $user = '';

    if ($userCheck === false) {
        return redirect('admin/login');
    } else {
        $user = auth()->guard('admin')->user();
    }

    if ($user->id === 1) {
        return true;
    }

    $minutes = 5;
    $permissions = Cache::remember('permissions_'.$user->id, $minutes, function () use ($user) {
        return explode(',', $user->permission->permission);
    });

    $permissions = array_flatten($permissions);

    return in_array($permission, $permissions);
}

I use it like this in the blade/view.

@if(can('admins'))
    <a href="{{ url(getLocal().'/admin/admins') }}" class="nav-link nav-toggle">
@endif

However, routes ignore the function and open all the routes. I use the function in routes like the following. Any ideas?

if (can('admins')) {
    Route::get('home', 'Admin\AdminController@index')->name('admin.home');
    Route::get('/admins/{id}/edit', 'Admin\AdminController@edit')->name('admins.edit');
}

Upvotes: 0

Views: 1179

Answers (1)

lagbox
lagbox

Reputation: 50481

Your routes don't need to be conditional. Define all the routes you need then you can restrict access to them with something like middleware. You can create a simple middleware that takes a parameter and calls your can function in app/Http/Middleware/CanDoIt.php:

namespace App\Http\Middleware;

use Closure;

class CanDoIt
{
    public function handle($request, Closure $next, $permission)
    {
        if (! can($permission)) {
            // redirect to some where else
        }

        // allow the request to pass through
        return $next($request);
    }
}

You can go into app/Http/Kernel.php and add your middleware to the $routeMiddleware array there:

protected $routeMiddleware = [
    ...
    'check' => \App\Http\Middleware\CanDoIt::class,
];

Then you can assign that middleware to your group of routes you want to restrict by can('admins')

Route::middleware('check:admins')->group(function () {
    Route::get('home', 'Admin\AdminController@index')->name('admin.home');
    Route::get('/admins/{id}/edit', 'Admin\AdminController@edit')->name('admins.edit');
});

I didn't name the middleware can as there is probably already a middleware named can registered for Authorization.

Laravel 6.x Docs - Middleware - Defining Middleware

Laravel 6.x Docs - Middleware - Middleware Parameters

Upvotes: 1

Related Questions