How to create link to call the resource destroy?

0

I have a view blade 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, that is, I have to submit the Delete option via DELETE method. Any ideas how to do this?

    
asked by anonymous 18.12.2016 / 00:47

1 answer

0

You should change the link to a form, as follows:

Replace this:

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

So:

<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 style you want to keep the link. You should capture the link click event and submit the form dynamically.

Assuming you use jQuery, the code will be + - this (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 almost forgot. The DELETE method is not supported by HTML in form. Then you must post, through a field of type "hidden" the method used. + - Thus.

 <input type="hidden" name="_method" value="delete"/>
    
18.12.2016 / 02:52