dongmu6578 2016-07-02 13:28
浏览 100
已采纳

除了点击之外,Laravel删除所有帖子

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:

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

My 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. Any help? Thank you.

  • 写回答

1条回答 默认 最新

  • douye1876 2016-07-02 13:37
    关注

    It's because the Post::where('id', $post_id)->first(); is not finding the post with the ID. Change it to Post::where('id', $post_id)->firstOrFail(); and it will throw an exception, which you can catch (Illuminate\Database\Eloquent\ModelNotFoundException).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路