0

I am trying to hit my destroy API below enter image description here

Gives me an error

"Call to a member function delete() on null"

Please help

my route definition in web.php is `

Route::resource('posts', 'postcarController'); my controller code is as below

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\PostModell;
use Illuminate\Support\Facades\Auth;

class postcarController extends Controller
{
   public function __construct()
    {
        $this->middleware('auth');
    }

   public function destroy($id)
    {
        //PostModel::where('id',$id)->delete();
         $post = PostModel::find($id);
        if($post!=null){
          $post->delete();
         return response()->json([
            'message' => 'book deleted',
        ], 200);
   }

   }
}

`I changed my url to http://127.0.0.1:8000/posts/3 appropriately and get error

The page has expired due to inactivity.

Please refresh and try again.

6
  • probably you don't have any record with that id, check your db record Commented Feb 4, 2018 at 7:02
  • I have 50 records from 1 yo 50 Commented Feb 4, 2018 at 7:07
  • try dd($post) and see if there any records exists Commented Feb 4, 2018 at 7:08
  • yes i have 50 records Commented Feb 4, 2018 at 7:10
  • could you please share what dd($post) gives Commented Feb 4, 2018 at 7:10

1 Answer 1

2

Rather than fetching the record and then deleting it, you could do it with one line like -

PostModel::where('id',$id)->delete();

Or you could check if record exists with that id or not and than delete it -

$post = PostModel::find($id);
if($post!=null){
  $post->delete();
  return //your new response;
}

return //response with message that no record exits
Sign up to request clarification or add additional context in comments.

8 Comments

@DENNISKITHINJI see my updated answer, it may help you
still the same error persist "Call to a member function delete() on null"
please share your controller code with route definition and did you really updated your code with my code as there is no way it could give such error
This is my route definition in web.php Route::resource('posts', 'postcarController');
please add this to your question with postcarController code
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.