// 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