【问题标题】:Laravel delete all posts except that i clickedLaravel 删除除了我点击的所有帖子
【发布时间】:2016-11-04 18:25:37
【问题描述】:

我尝试通过单击删除按钮来删除帖子,但我遇到了问题。如果我点击删除按钮,它会删除该用户的所有帖子,除了我点击的那个帖子。 有什么问题?

我的路线.php:

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

我的 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!']);
}

我的帖子模型:

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

我的用户模型:

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

和仪表板:

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

我正在使用 Laravel v5.2.39。有什么帮助吗?谢谢。

【问题讨论】:

    标签: php laravel controller routes dashboard


    【解决方案1】:

    这是因为Post::where('id', $post_id)-&gt;first(); 没有找到带有 ID 的帖子。把它改成Post::where('id', $post_id)-&gt;firstOrFail();,它会抛出一个异常,你可以捕获它(Illuminate\Database\Eloquent\ModelNotFoundException)。

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 2014-04-20
      • 2014-08-02
      • 2019-02-20
      • 2018-11-12
      • 2017-07-03
      • 1970-01-01
      相关资源
      最近更新 更多