简体   繁体   中英

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:

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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