2016-07-02 7 views
0

をクリックしたことを除いて、すべての投稿を削除します。私が「削除」ボタンをクリックすると、そのユーザーがクリックした投稿以外のすべての投稿が削除されます。 問題が何ですか?Laravelは私が削除ボタンをクリックすると投稿を削除しようとするが、私は問題を抱えている

私のroutes.php:

Route::get('deletepost/{post_id}', '[email protected]')->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!']); 
} 

マイPostモデル:

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

マイ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を使用しています。どんな助け?ありがとうございました。

答えて

0

Post::where('id', $post_id)->first();はIDとポストを見つけていないからです。それをPost::where('id', $post_id)->firstOrFail();に変更すると、例外がスローされます(Illuminate \ Database \ Eloquent \ ModelNotFoundException)。

+0

ありがとうございました。 –

関連する問題