Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make button visible once to admin-type user in Laravel?

I want to make ADD button only visible to admin-type user. My code looks like this:

@foreach($users as $user)
  @if(Auth::user()->type=='admin')
    <a href="{{ route('User.create', ['id'=>$user->id ]) }}" class="btn btn-default</i> ADD</a>
  @endif
@endforeach

But, it returns lot of ADD button according to number of all users because of foreach loop. If I remove foreach loop, it will show error:

Undefined variable: user

How can I solve this problem?

like image 218
irham dollah Avatar asked Jan 20 '26 05:01

irham dollah


2 Answers

It's because of you are removing the foreach , but using the variable $user again inside the routes . Please remove the $user->id and instead, use Auth::user()->id .

  @if(Auth::user()->type=='admin')
    <a href="{{ route('User.create', ['id'=>Auth::user()->id ]) }}" class="btn btn-default</i> ADD</a>
  @endif
like image 150
farooq Avatar answered Jan 23 '26 07:01

farooq


You do not need to use foreach loop to check authenticated user having type admin

You need to remove passing id into the user.create route

@if(Auth::user()->type == 'admin')
<a href="{{ route('User.create') }}" class="btn btn-default</i> ADD</a>
@endif
like image 31
Lizesh Shakya Avatar answered Jan 23 '26 08:01

Lizesh Shakya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!