Update record after find method in lavavel

You can update record after find method by passing the primary key of record to find() method and run update() method on record.

Answers 1
  • Update record using find() method with static value in laravel 8

    use App\Http\Controllers\HomeController;
    Route::get('/update-record',[HomeController::class, 'updateRecord']);
    //Import post model in controller
    use App\Models\Post;
    //Controller's method to update record with static value
    public function updateRecord(){
        $id = 1;
        $post = Post::find($id)->update(['description'=> 'Lorem ipsum']);
        echo $post;

    Output :

    If record exists with specific argument value and update query executed successfully


    If record does not exists and update query not executed successfully

    Error : Call to a member function update() on null

     The error Call to a member function update() on null means that Post::find($id) returned null. This may be because $id is itself null, or the value of $id does not exist in the id column of the posts table. 

    You have to check the $id value should not be null and after that you have to check the record with this id (value) exists in the table. It will return 1 if everything is ok else it will return Call to a member function update() on null.

  • Back to code snippet queries related laravel