Home > other >  Getting the user's role permission assigned in blade and controller
Getting the user's role permission assigned in blade and controller

Time:02-10

We have created a format where user can be assigned with role and each role have specific permissions. We are using laravel spatie permission library.

When trying to get the permission assigned to user or not it state the error as below:

Error :

Call to a member function contains() on string {"userId":1,"exception":"[object] (Error(code: 0): Call to a member function contains() on string at C:\\xampp\\htdocs\
olesPermission\\itm-encode\\vendor\\spatie\\laravel-permission\\src\\Traits\\HasPermissions.php:288)
[stacktrace]

Code :

    public function index(){
        $user = User::find(auth()->user()->id);
        dd($user->hasPermissionTo('Ticket-Handler-Wise'));
        return view('roles_permission.new_index');
    }

same error is on blade when tryng to access the permission with can. Can anyone help that how we can acheive this.

User Model:

<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\Group;
use Storage;
use DB;
use stdClass;
use Carbon\Carbon;
use Exception;
use Log;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable;
    use SoftDeletes;
    use HasRoles;
    protected $guarded = [];
    protected $hidden = [
        'password', 'remember_token',
    ];

**Permission.php : **

<?php

return [

    'models' => [

        /*
         * When using the "HasPermissions" trait from this package, we need to know which
         * Eloquent model should be used to retrieve your permissions. Of course, it
         * is often just the "Permission" model but you may use whatever you like.
         *
         * The model you want to use as a Permission model needs to implement the
         * `Spatie\Permission\Contracts\Permission` contract.
         */

        'permission' => Spatie\Permission\Models\Permission::class,

** blade.php : **

@section('content')
<section >
    @can('Ticket-Handler-Wise')
        hello
    @else
        No
    @endcan

CodePudding user response:

  •  Tags:  
  • Related