wllmwng
wllmwng

Reputation: 11

Laravel 5.4 Destroy POST function is going wrong

I'm working on a news thread on laravel 5.4. My problem is that whenever a user want to delete a post, if there is a post that has the same id as him, it will delete it instead of the post I originally wanted to destroy. But if there is isn't, he can delete his post without a problem. For example, my user has an id 4 and want to delete his post which has an id of 12. The first time I click on my delete link, it will delete the post with the id of 4. When this one doesn't exist anymore, he can destroy the post with the id of 12.

The function in the controller

/**
 * Remove the specified resource from storage.
 *
 * @param  \App\StartUpPost  $startUpPost
 * @return \Illuminate\Http\Response
 */
public function destroy(StartUpPost $startUpPost)
{
    $post = StartUpPost::find($startUpPost);
    $post->delete();

    return redirect('startup/home') -> with('success', 'Post deleted !');
}

The route

Route::get('/StartUpPost/{startUpPost}/delete',[
    'uses' => 'StartUpPostController@destroy',
    'as'=>'startUpPost.delete'
]);

The link in HTML

<a href="{{route('startUpPost.delete', ['startUpPost' => $startuppost->id])}}">Delete</a>

The model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class StartUpPost extends Model
{
    protected $table = 'start_up_posts';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'content','startup_id','image',
    ];

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

    public function startUpComments() {
        return $this->hasMany('App\StartUpComment');
    }
}

What am I doing wrong?

Upvotes: 1

Views: 629

Answers (1)

Onix
Onix

Reputation: 2179

Your controller function should be like this: (no need to search for the item again, you already have it with this in your fucntion parameters StartUpPost $startUpPost)

public function destroy(StartUpPost $startUpPost)
{
    $startUpPost->delete();
    return redirect('startup/home') -> with('success', 'Post deleted !');
}

Check the button before you click it, the mistake must be in your action link to delete the post, check how you load each button

You have $startuppost->id . so which post is it? I guess it takes the first one. The problem might be in the query you select the $startuppost before deleting it

Upvotes: 0

Related Questions