php - How can I use Middleware to define a section of a blade template? -


i have navigation bar i'd show link admin dashboard if user logged in admin. if not, should display nothing. have similar set guests e.g.

@if (auth::guest())         <li><a href="{{ url('/auth/login') }}">login</a></li>         <li><a href="{{ url('/auth/register') }}">register</a></li>     @else         <li class="dropdown">             <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">{{ auth::user()->name }} <span class="caret"></span></a>             <ul class="dropdown-menu" role="menu">                 <li><a href="{{ url('/profile') }}">profile</a></li>                 <li><a href="{{ url('/auth/logout') }}">logout</a></li>             </ul>         </li> @endif 

but how can logged in user , admin? have

<ul class="nav navbar-nav">     <li><a href="{{ url('/') }}">home</a></li>     @if (auth::guest())      @else     <li><a href="{{ url('/admin') }}">admin dashboard</a></li>     @endif </ul> 

i have middleware set on admin route so

route::get('admin', ['middleware' => 'admin', 'uses' => 'admincontroller@index']); 

which looks like

public function handle($request, closure $next) {     if ($request->user()->role != 1)     {         return redirect('home');     }      return $next($request); } 

and that's fine, don't know how define section of blade template.

looks user model has attribute named role, can this:

<ul class="nav navbar-nav">     <li><a href="{{ url('/') }}">home</a></li>     @if (auth::user()->role != 1)          {{-- not admin user --}}     @else         {{-- admin user --}}     @endif </ul> 

if not case, need add new attribute user model. way able emulate code above.

for better code structure , order, suggest make fuction inside of user model this:

public function isadmin(){     return (\auth::check() && $this->role == 1); } 

or 1 check if regular user:

/** user authenticated not admin  */ public function isregular(){     return (\auth::check() && $this->role != 1); } 

then, in application , views can use them like:

@if (auth::user()->isregular())      {{-- not admin user --}} @else     {{-- admin user --}} @endif 

or

@if (auth::user()->isadmin())      {{-- admin user --}} @else     {{-- not admin user --}} @endif 

Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -