提问者:小点点

如何删除laravel 5中的帖子资源?


拉威尔5版

我正在处理一个新的laravel 5版本的项目,由于某些原因,我无法删除帖子,当我按下delete键时,它只会将我重定向到id为/post/3的帖子显示页面,我会看到一个空白的白页,当我返回到index view时,我会看到所有的帖子,而其中一篇没有被删除。以下是我的资料:

发布迁移文件

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreatePostsTable extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('title')->default('');
            $table->string('slug')->default('');
            $table->text('body');
            $table->integer('author_id');
            $table->string('author');
            $table->string('featured_image');
            $table->softDeletes();
            $table->timestamps();
        });
    }


    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('posts');
    }

}

后置控制器

use Input;
use Redirect;
use Storage;
use SirTrevorJs;
use STConverter;
use Validator;
use Image;
use Boroughcc\Post;
use Boroughcc\Http\Requests;
use Boroughcc\Http\Controllers\Controller;

use Illuminate\Http\Request;

class PostsController extends Controller {
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', compact('posts'));
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update(Post $post)
    {
        //
        $this->middleware('auth');
        $input = array_except(Input::all(), '_method');
        $post->update($input);

        return Redirect::route('posts.show', $post->slug)->with('message', 'Post updated.');
    }
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy(Post $post)
    {
        //
        //$post = Post::findOrFail($id);
        $post->delete();
        if($post->delete()) { 
            return Redirect::route('posts.index')->with('message', 'Post deleted.');
        }
    }

}

据我所知,这是好的,但我认为这是删除的方法,这一切都搞砸了。在我的路由文件中,我设置了路由资源,以便在php artisan中显示路由,我可以看到这样的销毁路由:

|        | GET|HEAD                       | posts                                                 | posts.index   | Boroughcc\Http\Controllers\PostsController@index                 |            |
|        | GET|HEAD                       | posts/create                                          | posts.create  | Boroughcc\Http\Controllers\PostsController@create                |            |
|        | POST                           | posts                                                 | posts.store   | Boroughcc\Http\Controllers\PostsController@store                 |            |
|        | GET|HEAD                       | posts/{posts}                                         | posts.show    | Boroughcc\Http\Controllers\PostsController@show                  |            |
|        | GET|HEAD                       | posts/{posts}/edit                                    | posts.edit    | Boroughcc\Http\Controllers\PostsController@edit                  |            |
|        | PUT                            | posts/{posts}                                         | posts.update  | Boroughcc\Http\Controllers\PostsController@update                |            |
|        | PATCH                          | posts/{posts}                                         |               | Boroughcc\Http\Controllers\PostsController@update                |            |
|        | DELETE                         | posts/{posts}                                         | posts.destroy | Boroughcc\Http\Controllers\PostsController@destroy

使用“删除”按钮发布表单

在这里,我有一个简单的按钮,告诉表单从索引列表中删除资源并从表中获取它。

{!! Form::open(array('class' => 'form-inline', 'method' => 'DELETE', 'route' => array('posts.destroy', $post->id))) !!}
                    <li>
                        <img src="{!! $post->featured_image !!}" alt="" />
                        <a href="{{ route('posts.show', $post->id) }}">{{ $post->title }}</a>
                    </li>
                    (
                        {!! link_to_route('posts.edit', 'Edit', array($post->slug), array('class' => 'btn btn-info')) !!},
                        {!! Form::submit('Delete', array('class' => 'btn btn-danger')) !!}
                    )
                {!! Form::close() !!}

我得到的是什么都没有,没有帖子被删除。任何正确的答案或指向正确的地方都会很棒。


共3个答案

匿名用户

我不知道如何使用静态类表单,但几天前我仅使用HTML代码就发现了这个问题。

这不起作用:

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

这很好:

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

资料来源:

  • http://laravel.io/forum/01-19-2015-delete-route-doesnt-work-page-not-found
  • https://laracasts.com/discuss/channels/general-discussion/how-to-updatedelete-using-forms-and-restful-controllers

匿名用户

如何向用户邮寄申请表:

查看:

<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::group(['middleware' => 'web'], function () {
 Route::delete('/home/destroy',[
  'as'=> 'home.destroy',
  'uses'=> 'homeController@destroy',
 ]);
});

控制器:

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');
  }
}

如果()仅用于防止用户删除另一个用户,而Auth::logout()用于清除会话中的用户数据(如果您不使用用户,则用户将不需要这些数据),则必须使用==不===比较$id和Auth::user()-

这种方式相当于使用get与此代码:

查看:

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

路线:

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

控制器:

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');
  }
}

匿名用户

您想在这里使用路由模型绑定。

您可以转到应用程序/提供商/RouteServiceProvider.php文件中的引导方法,并添加int:

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

要告诉laravel,您提供的posts参数(在route:list中可见)应绑定到Post`模型(laravel默认使用id)

或者你也可以在app/Http/routes.php中使用:

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