How can I delete a post resource in laravel 5?

淺唱寂寞╮ 提交于 2019-12-05 13:45:41

I don't know how to do it with the static class Form but I found this problem some days ago using only HTML code.

This doesn't work:

<form action="{{ action('Controller@destroy') }}" method="DELETE">
...
</form>

This works fine:

<form action="{{ action('Controller@destroy') }}" method="POST">
    <input type="hidden" name="_method" value="DELETE">
    ...
</form>

Sources:

You want to use Route model binding here.

You can go to the boot method in your app/Providers/RouteServiceProvider.php file and add in int:

$router->bind('posts','Boroughcc\Post');

to tell laravel the posts parameter (it's visible in route:list you provided) should be bound to thePost` model (Laravel by default will use id)

or you can do the same in app/Http/routes.php using:

Router::bind('posts','Boroughcc\Post');

to delete a model, do this

$model -> find($id);
$model -> delete();

or simply

$model -> destroy($id);

to delete multiple rows

$model -> destroy ([1,2,3]);

how to send form by post applied to users:

View:

<form class="" action="{{ url('/home/destroy') }}" method="post">
  <li><button type="submit"><i class="fa fa-btn fa-sign-out"></i>Destroy user</button></li>
  <input type="hidden" name="id" value="{{Auth::user()->id}}">
  {{ method_field('DELETE') }}
  {!! csrf_field() !!}
</form>

Route:

Route::group(['middleware' => 'web'], function () {
 Route::delete('/home/destroy',[
  'as'=> 'home.destroy',
  'uses'=> 'homeController@destroy',
 ]);
});

Controller:

use app\User;
use Illuminate\Support\Facades\Auth;

protected function destroy(Request $request)
{
  $id= $request->id;
  if (Auth::user()->id == $id){
    $user= User::find($id);
    $user-> delete();
    Auth::logout();
    return redirect()->route('welcome');
  }else{
    return redirect()->route('home');
  }
}

if() is only to prevent a user deletes another and Auth::logout() is to clear user data in the session if you do not work with users will not need them, you must use == not === to compare $id and Auth::user()->id, $id works as string, and Auth::user()->id works as number.

This way is equivalent to using get with this code:

View:

<li><a href="{{ url('/home/delete', Auth::user()->id) }}"><i class="fa fa-btn fa-sign-out"></i>Delete user</a></li>

Route:

Route::group(['middleware' => 'web'], function () {
  Route::get('/home/delete/{id}', 'homeController@delete');
});

Controller:

protected function delete($id)
{
  if (Auth::user()->id == $id){
    $user= User::find($id);
    $user-> delete();
    Auth::logout();
    return redirect()->route('welcome');
  }else{
    return redirect()->route('home');
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!