Dominykas Česonis
Dominykas Česonis

Reputation: 43

laravel a href validation

I would like to ask if it is possible to validate a href element in laravel.


For example, I'm having a bunch of people responses in my guest book and each user is able do delete his posts. I'm deleting it like this:

 <div class="col-lg-2">
   <ul class="list-unstyled trash">
      <li> 
        <a href="/responses/{{$response->id}}">       
         <span onclick="alertDialog()" class="glyphicon glyphicon-trash"></span></a></li>
         <li><button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#{{$response->id}}">Edit</button></li>
   </ul>
 </div>

Unfortunately, every single user can change "/responses/{{$response->id}}"> id via browser developer tools and delete other user's responses. Is there any possible solutions to prevent this issue?

Upvotes: 1

Views: 345

Answers (3)

Just check the logged user before rendering that html section:

<div class="col-lg-2">
   <!-- assuming post is your variable and user is a property which references the user who created the record -->
   @if($post->user == Auth::id())
   <ul class="list-unstyled trash">
      <li> 
        <a href="/responses/{{$response->id}}">       
         <span onclick="alertDialog()" class="glyphicon glyphicon-trash"></span></a></li>
         <li><button type="button" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#{{$response->id}}">Edit</button></li>
   </ul>
   @endif
 </div>

This way only the user who owns the post will be able to see the button in the html.

Upvotes: 2

Sapnesh Naik
Sapnesh Naik

Reputation: 11656

You should make /responses/{{$response->id}} a POST route and verify that the passed id matches with the authenticated users id. ( Auth::user()->id;)

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

You need to use policies to check if the user that tries to delete a record is its owner:

public function delete(User $user, Model $model)
{
    return $user->id === $model->user_id;
}

Or you can do it manually in a controller method:

if (auth()->id() === $model->user_id) {
    // Delete the record
}

Upvotes: 2

Related Questions