Posted on • Updated on

Laravel Model Const

author

Kai

// Newbie

#PostController.php

class PostController extends Controller
{
    ...
    public function index()
    {
    	if(auth()->user()->role == 'superadmin'){
    		$posts = Post::all();
    	}else{
    		$posts = Post::where('author_id', auth()->id())
    	}
    	
        return view('posts.index', [
        'posts' => $posts
        ]);
    }
    ...
}

 

// Experienced

#User.php

class User extends Authenticatable
{
	...
	public const ROLE_SUPERADMIN = 'superadmin';
	...
}

#PostController.php

class PostController extends Controller
{
    ...
    public function index()
    {
    	if(auth()->user()->role == User::ROLE_SUPERADMIN){
    		$posts = Post::all();
    	}else{
    		$posts = Post::where('author_id', auth()->id())
    	}
    	
        return view('posts.index', [
        'posts' => $posts
        ]);
    }
    ...
}

We replaced superadmin with User::ROLE_SUPERADMIN and set its value in User Model

You can use model const in blade view as well

#index.blade.php

@if (auth()->user()->role == \App\Models\User::ROLE_SUPERADMIN)
	I am superadmin! ğŸ˜Ž
@else
	I am normal user! 🤠
@endif

 

end of article

Related Posts

Join Our Newsletter

Want the latest & greatest from our blog straight to your inbox with some exclusive offers from our partners and sponsors?

We won't spam. Promise.