Skip to content
Advertisement

How to display link delete to auth user in Laravel?

I’m having a simple message/comment features. The message can be deleted by using SoftDeletes function in Laravel. However, I want to make the message can be deleted or the link message being display by the logged-in user only. They cannot delete other’s message. So, here is my code in

message.blade.php

<div class="panel-heading">Message</div>
   <div class="panel-body">
       <div class="row">
          <form id="message-form" method="post" action="{{ route('message.store') }}" >
          {{ csrf_field() }}
          <input type="hidden" name="contractor_id" value="{{$contractor->id}}" >
          <input type="hidden" name="admin_id" value="{{$contractor->added_by}}" >
              <div class="row" style="padding: 10px;">
                 <div class="form-group">
                     <textarea class="form-control" name="message" placeholder="Write something..." required=""></textarea>
                 </div>
              </div>
              <div class="row" style="padding: 0 10px 0 10px;">
                 <div class="form-group">
                     <input type="submit" class="btn btn-primary" style="width: 100%" name="Submit">
                 </div>
              </div>
          </form>
      </div>
   </div>
</div>

<div class="row">
    <div class="panel-heading">Replies</div>
        <div class="panel-body comment-container scrollable-panel" >
        @foreach($message as $m)
            <i><b> {{ $m->name }} </b></i>&nbsp;&nbsp;
            <span> {{ $m->message }} </span>
            <div style="margin-left:10px;">
            <a href="#" class="delete" message-id="{{$m->id}}" message-text="{{$m->message}}">Delete</a>&nbsp;&nbsp;
            <span> {{date('g:i A d/m/Y ', strtotime($m->created_at))}}</span>
       </div>
       @endforeach
</div>

I already tried by using @if (Auth::check()) but there is no difference, the delete link still show up for all users.

@if (Auth::check())
   <a href="#" class="delete" message-id="{{$m->id}}" message-text="{{$m->message}}">Delete</a>&nbsp;&nbsp;
@endif

How can I make it?

Advertisement

Answer

I assume you have user_id in messages table or any relationship you have created so you need to do like this

@if (Auth::check() && $m->user_id == auth()->id()) //here $m->user_id is condition you need to change as per your db structure 
   <a href="#" class="delete" message-id="{{$m->id}}" message-text="{{$m->message}}">Delete</a>&nbsp;&nbsp;
@endif

or you can create policy for clean code as Laravel recommend to use that
https://laravel.com/docs/8.x/authorization#creating-policies

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement