Thursday, February 21, 2019

Adding isAdmin() function in Model User in Laravel

Adding isAdmin() function in Model User in Laravel

It is necessary to create a helper to identify whether the login user is an administrator. To do that, we can add a helper function to Model User.

app\User.php

public function isAdmin() {
  return $this->is_admin == true;
}

By checking the field is_admin, we can get the answer.

Thus, the isAdmin() function can be used by index.blade.php for showing the functions that only available for the administrator, such as “Add New Product”, “Edit Product” and “Delete Product”.

index.blade.php

<!-- Check if user is an administrator  -->   
@if(Auth::check() and (Auth::user()->isAdmin() == true))  
  <td><a href="{{ route('products.edit', $product->id) }}" 
  	class="btn btn-secondary">
  	<i class="fa fa-edit"></i>Edit</a></td>
  <td>
    <form method="post" action="{{ route('products.destroy', $product->id) }}">
  	  @method('DELETE')
  	  @csrf
  	  <button type="submit" class="btn btn-danger">
  	  <i class="fa fa-trash"></i>Delete</button>
  	</form>	
  </td>
@endif

Note that Auth::user()->isAdmin() may return null if the user is not login and it will make mistake. Therefor, we must check if the user is a login user by using Auth::check().

@if(Auth::check() and (Auth::user()->isAdmin() == true))
   :
@endif 

The isAdmin() function can be used to check if a login user is an administrator. It keeps guests and unauthorized users out of the functions only available for administrators in view files.

No comments:

Post a Comment