Currently, I have seeded 1 user with the role of admin, and every new user who registers will be assigned a role of user. The roles are in a table called roles, the users are in a table called users and the connection between these 2 is in a table called role_user. Now I can't exactly figure out how to, for example, change my header to include admin menu if the logged user is an admin.
Header.blade.php
<section class="header">
<div class="wrapper">
<nav class="navigation">
<ul>
<li><a href="{{ route('home') }}">Images</a></li>
@auth
<li><a href="{{ route('upload') }}">Upload</a></li>
<li class='logOut'><a href="{{ route('logout') }}">Logout</a></li>
@endauth
@guest
<li class="signUp">Sign Up</li>
<li class="logIn">Log In</li>
@endguest
</ul>
</nav>
</div>
</section>
Role.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users(){
return $this->belongsToMany('App\User');
}
}
User.php
<?php
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function images(){
return $this->hasMany('App\Image');
}
public function roles(){
return $this->belongsToMany('App\Role');
}
}
Database tables
Table - users
Columns - id, username, password
Table - roles
Columns - id, name, description
Table - role_user
Columns - id, user_id, role_id
Add this function to your model for checking role
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function roles(){
return $this->belongsToMany('App\Role');
}
public function hasRole($roleName){
$result = false;
foreach($this->roles as $role){
if($role->name == $roleName)
$result = true ;
}
return $result;
}
}
And in your views
@if((\Auth::check() && \Auth::user()->hasRole('admin')
@include('admin.nav')
@endif