How to create a link to call Resource Stroy?

Asked

Viewed 310 times

0

I have a Blade view with the following structure:

@forelse($posts as $p)
<tr>
    <td><a href="/post/{{ $p->id }}">{{ $p->titulo }}</a></td>
    <td>{{ $p->status_mutator }}</td>
    <td>{{ $p->user->name }}</td>
    <td>{{ $p->created_at->format('d/m/Y à\s H:i:s')}}</td>
    <td>
        <a href="/painel/post/{{ $p->id }}/edit">Editar</a> / 
        <a href="/painel/post/{{ $p->id }}">Excluir</a>
    </td>
</tr>
@empty
<tr>
    <td colspan="5">Não existem posts para serem listados</td>
</tr>
@endforelse

But my route uses the Resource structure, IE, I have to submit the Delete option via DELETE method. Any idea how to do this?

  • Deleting something through a simple link is unsafe. Better you create a form, set the "DELETE" method for the route and use a button or an event in a link that submits the form

  • Yes the idea is this. As I said I want to use the method DELETE (DELETE verb) via form. I just need help to build something in Javascript that captures the id of the clicked link and submit the form

1 answer

0

You should exchange the link for a form, as follows:

Replace that:

<td>
        <a href="/painel/post/{{ $p->id }}/edit">Editar</a>  
        <a href="/painel/post/{{ $p->id }}">Excluir</a>
    </td>

That’s why:

<td>
    <a href="/painel/post/{{ $p->id }}/edit">Editar</a>  
    <form actio="/painel/post/{{ $p->id }}" ...>
        <button type="submit">Excluir</buttom>
    </form>
</td>

If for the sake of style you want to keep the link. You must capture the link click event and submit the form dynamically.

Assuming you use jQuery, the code will be +- this(I have not tested):

HTML:

<td>
    <a href="/painel/post/{{ $p->id }}/edit">Editar</a> / 
    <form actio="/painel/post/{{ $p->id }}">
        <a href="#" class="link-delete">Excluir</a>
    </form>
</td>

Javascript:

<script>

   $(".link-delete").click(function(event){
      $(event.target).parent().submit();
   });

</script>

UPDATE I forgot. The DELETE method is not supported by the form HTML. Then you should post, through a field of type "Hidden" the method used. + - Like this.

 <input type="hidden" name="_method" value="delete"/>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.