简体   繁体   English

Laravel删除除我单击以外的所有帖子

[英]Laravel delete all posts except that i clicked

I try to delete post by click on delete button, but I have problem. 我尝试通过单击删除按钮删除帖子,但是我有问题。 If i click on delete button, it delete all posts by that user except that post I've clicked on. 如果我单击删除按钮,它将删除该用户的所有帖子,但我单击过的帖子除外。 Whats the problem? 有什么问题?

My routes.php: 我的routes.php:

Route::get('deletepost/{post_id}', 'PostController@getDeletePost')->name('delete');

My PostController: 我的PostController:

public function getDeletePost($post_id){
  $post = Post::where('id', $post_id)->first();
    if(Auth::user() != $post->user){
      return redirect()->back();
    }
  $post->delete();
  return redirect()->route('dashboard')->with(['message' => 'Successfully deleted!']);
}

My Post model: 我的帖子模型:

public function user(){
  return $this->belongsTo('App\User');
}

My User model: 我的用户模型:

namespace App;

use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;

class User extends Model implements Authenticatable
{
    use \Illuminate\Auth\Authenticatable;

    public function posts(){
    return $this->hasMany('App\Post');
   }
}

And dashboard: 和仪表板:

@if(Auth::user() == $post->user)
            <a href="#">Edit</a>
            <a href=" {{ route('delete', ['post_id' => $post->id]) }}">Delete</a>
@endif

I am using Laravel v5.2.39. 我正在使用Laravel v5.2.39。 Any help? 有什么帮助吗? Thank you. 谢谢。

It's because the Post::where('id', $post_id)->first(); 这是因为Post::where('id', $post_id)->first(); is not finding the post with the ID. 找不到带有ID的帖子。 Change it to Post::where('id', $post_id)->firstOrFail(); 将其更改为Post::where('id', $post_id)->firstOrFail(); and it will throw an exception, which you can catch (Illuminate\\Database\\Eloquent\\ModelNotFoundException). 它将引发一个异常,您可以捕获该异常(Illuminate \\ Database \\ Eloquent \\ ModelNotFoundException)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM