Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

laksh's avatar
Level 1

Roles and Permission doesn't working

i have created a full roles and permission system without installing package but it doesn't working it works like a simple login can anyone suggest me something. Thanks in advance

0 likes
55 replies
laksh's avatar
Level 1

Here's my code in service provider

namespace App\Providers;

use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\Gate; use App\Models\permission;

class PermissionServiceProvider extends ServiceProvider { public function register() { // }

public function boot()
{
    try {
        permission::get()->map(function ($permission){
            Gate::define($permission->slug, function ($user) use ($permission){
                return $user->hasPermissionTo($permission);
            });
        });
    } catch (\Exception $e){
        report($e);
        return false;
    }
    
    Blade::directive('role', function ($role) {
        return "if(auth()->check() && auth()->user()->hasRole({$role})) :"; 
    });
    
    Blade::directive('endrole', function ($role) {
        return "endif;"; 
    });
}

}

laksh's avatar
Level 1

i dont know whats happeing but is there any bug in it can you check?

Sinnbeck's avatar

@laksh maybe start by explaining what happens. "Doesn't work" isn't much to go by

laksh's avatar
Level 1

@Sinnbeck yeah so i want that if ant other employee try to edit anything will get error but in my case the edit window will open and this will print

if(auth()->check() && auth()->user()->hasRole('manager')) :

but not giving error

Sinnbeck's avatar

@laksh It isnt written as php

    Blade::directive('role', function ($role) {
        return "<?php if(auth()->check() && auth()->user()->hasRole({$role})) : ?>"; 
    });
    
    Blade::directive('endrole', function ($role) {
        return "<?php endif; ?>"; 
    });
Sinnbeck's avatar

@laksh You said no error? Is it showing the same output? Try php artisan view:clear

laksh's avatar
Level 1

@Sinnbeck after that now it's giving an error here's error : syntax error, unexpected 'endif' (T_ENDIF), expecting end of file (View: D:\xampp\htdocs\demo\resources\views\posts\edit.blade.php)

laksh's avatar
Level 1

@Sinnbeck

    Blade::directive('role', function ($role) {
        return "<?php if(auth()->check() && auth()->user()->hasRole({$role})); ?>"; 
    });
    
    Blade::directive('endrole', function ($role) {
        return "<?php endif; ?>"; 
    });
}
Sinnbeck's avatar

Maybe try without {}

    Blade::directive('role', function ($role) {
        return "<?php if(auth()->check() && auth()->user()->hasRole($role)) : ?>"; 
    });
    
    Blade::directive('endrole', function ($role) {
        return "<?php endif; ?>"; 
    });
laksh's avatar
Level 1

@Sinnbeck i am using this with the help of @role

@role('manager')

<div class="container">
	<div class="row justify-content-centre">
		<div class="col-md-8">
			<div class="card">
				<div class="card-header">{{ __('Edit Post') }}</div>
				
				<div class="card-body">
					@if(session('status'))
						<div class="alert alert-success">
							{{ session('status') }}
						</div>
					@endif
					
					<form action="{{ route('update', $post->id) }}" method="post">
						@csrf
						
						@method('PUT')
						<div class="form-group">
							<label for="">Post Tittle</label>
							<input type="text" name="tittle" class="form-control" value = "{{ ($post->tittle) }}">
						</div>
						
						<div class="form-group">
							<label for="">Post Body</label>
							<textarea name="body" id="" cols="30" rows="10" class="form-control" >{{ $post->body }}</textarea>
						</div>
						
						
						<button type="submit" class="btn btn-primary">Submit</button>
					
					</form>
				</div>
			</div>
		</div>
	</div>
</div>

@endrole

Sinnbeck's avatar

@laksh Cant say what you are doing wrong. It works for me. Did you remove {} from the directive like i told you?

Sinnbeck's avatar

@laksh Ok Im not sure how to help you then. I copied the blade code into a new blade file with nothing else, and copied over the two directives from my last example, and it worked. Maybe you have something that you arent showing? Does it work if you rename the directives to something else? Like "rolecheck" and "endrolecheck"

laksh's avatar
Level 1

@Sinnbeck umm basically i want that if i login from developer id it doesn't show me the edit view but in my case it is showing me the view without error

laksh's avatar
Level 1

@Sinnbeck yeah there is no error but its not working like how i want to work that

Sinnbeck's avatar

@laksh Ok. I dont know how I can help with that? What is happening and what do you expect?

Snapey's avatar

so your actual issue is writing blades directives, not your permissions?

make sure you clear the view cache each tome you change the blade design

I think the issue is that you can't just pass the role name in as a simple variable. im checking my notes but it's a long time since i bothered creating blade extensions

try this instead

    Blade::directive('role', function ($role) {
        return "<?php if(auth()->check() && auth()->user()->hasRole('{$role}')); ?>"; 
    });

notice the quotes around the role

clear all views, load the page, then find the file just created in your storage/framework/views folder

open it and check the php that was generated by your blade extension

laksh's avatar
Level 1

@Snapey yeah i am clearing the cache everytime i changed the view

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

@Snapey It autocatically quotes it :)

This is from the compiled file

<?php if(auth()->check() && auth()->user()->hasRole('manager')) : ?>
Sinnbeck's avatar

@laksh Can you please spend 2 minutes explaining exactly what is happening and what you expect to happen?

laksh's avatar
Level 1

@Sinnbeck basically i want that i made a blog page and on that page a developer can only will create not edit means developer has not permission to edit the blog but in my case the developer can able to edit the blogs which is wrong

Snapey's avatar

@laksh are you sure the developer is not also manager. can a user have more than one role?

you created the gates, but how is permissions assigned to a user?

Sinnbeck's avatar

@laksh What does this give you?

@dd(auth()->user()->hasRole('manager')))
Snapey's avatar

@laksh

you created the gates, but how is permissions assigned to a user?

laksh's avatar
Level 1

@Snapey i don't know what do you mean to say how permissions can be assigned

Snapey's avatar

@laksh what gives the user the role of 'Manager' or 'developer'

laksh's avatar
Level 1

@Snapey i created two tables into database one is roles and one is permissions and from there the roles and permission were assigned to the manager and developer

laksh's avatar
Level 1

@Snapey when i create user manager this code is used by me to assigning permissions.

$manager = new User();

    $manager->name = 'manager';


    $manager->email = '[email protected]';


    $manager->password = Hash::make('4321');


    $manager->save();


    $manager->role()->attach($manag_role);


    $manager->permission()->attach($manag_perm);

    
laksh's avatar
Level 1

@Snapey yeah here it is

public function hasRole( ... $role){

    foreach ($role as $roles){
        if ($this->role->contains('slug',$roles)){
            return true;
        }
    }
    
    return false;
}
Snapey's avatar

@laksh bit by bit we get the information....

so role is a relationship on the user model, and the code you show is in the User model also but its a one to Many relationship but you have named it singular? Have you tested it even returns any roles?

Can you show your entire User model?

laksh's avatar
Level 1

@Snapey the code i show is in HasPermissionTrait file which was created by me so you want to see the whole file in which that code is written which was shown by me?

laksh's avatar
Level 1

@Snapey one thing i'll tell you is that on using @dd(auth()->user()->hasRole('manager')) code i get the response false means if i logged in from developer id and on clicking edit button i got that message so it means permissions were working?

Snapey's avatar

@laksh So you are sorted then.... all working? If not then you need to provide the code to help diagnose the issue

laksh's avatar
Level 1

@Snapey no it wasn't working i mean to say according to me permissions were assigned to users correctly but they don't give results

public function boot() { try { permission::get()->map(function ($permission){ Gate::define($permission->slug, function ($user) use ($permission){ return $user->hasPermissionTo($permission); }); }); } catch (\Exception $e){ report($e); return false; }

    Blade::directive('role', function ($role) {
        
        //return @dd(auth()->user()->hasRole('manager'));
        
        if (auth()->guest()){
            abort(Response::HTTP_FORBIDDEN);
        }else {
            return "if(auth()->check() && auth()->user()->hasRole({$role})) ;";
        }
        
    });
    
    Blade::directive('endrole', function ($role) {
        return "endif;"; 
    });
}
laksh's avatar
Level 1

the return response in this code print as it is on my page it won't render can you tell me what should i do for that?

Snapey's avatar

@laksh please format your code here

why does your blade directive not look like the earlier solution from @sinnbeck ? Blade directives MUST return strings with echo statements in them

laksh's avatar
Level 1

@Snapey you mean to say by using <? php tag in return string

Snapey's avatar

@laksh Blade extensions must return a string containing valid PHP code that will be included in the cached view file and then executed when that cached file is loaded.

It should not evaluate any run time data in the blade extension itself, but only prepare the code that will evaluate run time data later

So as Sinnbeck proposed

    Blade::directive('role', function ($role) {
        return "<?php if(auth()->check() && auth()->user()->hasRole($role)) : ?>"; 
    });
    
    Blade::directive('endrole', function ($role) {
        return "<?php endif; ?>"; 
    });
laksh's avatar
Level 1

@Snapey but in this code if part doesn't give any response and endif part gives error on using <?php

Snapey's avatar

@laksh This question has best answer so nothing else to do?

If not, show some errors.

Please or to participate in this conversation.