M.Milton M.Milton - 1 year ago 96
PHP Question

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();
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>

I am using Laravel v5.2.39. Any help? Thank you.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download