Search code examples
phplaravel-5.3

Delete a record using laravel delete function


I want to delete a record from my table named post. I am sending a param named tag in my view to delete a certain record against this tag. So here is my route

   Route::get('/delete' , array('as' =>'delete' , 'uses' => 'Postcontroller@deletepost'));

by this route i am delete my post against it's 'tag' field. my table has two column. one is tag and other is content My delete fucntion in PostController is

   public function deletepost($tag){

   $post = post::find($tag); //this is line 28 in my fuction
   $post->delete();
   echo ('record is deleted') ;
   }

I am send tag from my view but it is giving the following error

  ErrorException in Postcontroller.php line 28:
  Missing argument 1 for
  App\Http\Controllers\Postcontroller::deletepost()

Solution

  • Your action should look like this:

    use Illuminate\Http\Request;
    
    public function deletepost(Request $request) // add Request to get the post data
    {
        $tagId = $request->input('id'); // here you define $tagId by the post data you send
        $post = post::find($tagId);
        if ($post) {
            $post->delete();
            echo ('record is deleted!');
        } else {
            echo 'record not found!');
        }
    }