Home > OS >  Laravel 5.8: Creating default object from empty value
Laravel 5.8: Creating default object from empty value

Time:10-30

I'm working with Laravel 5.8 and I have added this code to my Controller:

public function denyRequest($id)
    {
        $findRequest = WithdrawWallet::find($id);
        $findRequest->status = 'cancelled';
        $findRequest->save();
        return redirect()->back();
    }

And here is route for this:

Route::get('{id}','Wallet\WalletController@denyRequest')->name('denyRequest');

Now I get this error:

ErrorException (E_WARNING) Creating default object from empty value

Which is referring to this:

enter image description here

So what's going really wrong here? How to fix this issue?

CodePudding user response:

Replace find with findOrFail:

$findRequest = WithdrawWallet::findOrFail($id);

CodePudding user response:

When you search for existing Withdraw Wallet with an id that doesnt exist, it will return null. and since you assign 'cancelled' as an object attribute on the variable, php will convert $findRequest to a default object (StdObject::class) to be able to assign the attribute to it.

One simple solution would be to use findOrFail() instead of find() wich will trigger an exception and return a 404 response on the request.

$findRequest = WithdrawWallet::findOrFail($id);
$findRequest->status = 'cancelled';
$findRequest->save();
return redirect()->back();

another suggestion (if you have soft delete on on the model and the id exists in the database) is to use withTrashed()

$findRequest = WithdrawWallet::withTrashed()->findOrFail($id);
        $findRequest->status = 'cancelled';
        $findRequest->save();
        return redirect()->back();
  • Related