Trying to get property of non-object laravel on command dispatch - laravel

I am using "Mapping Command Properties From Requests" getting this error
Trying to get property of non-object
My Code
use App\Command\CreateSomethingCommand;
public function store(Request $request)
{
$this->dispatchFrom(CreateSomethingCommand::class,$request,['user'=>Auth::User()->id]);
.....
}
Where as the command stated at laravel
https://laravel.com/docs/5.0/bus#dispatching-commands
Please Help!

The error is most likely triggered by this part of your code Auth::User()->id. If the user is not logged in then the result of Auth::user() will be null and since null is not an object you can't access the id property on it, thus throwing the exception:
Trying to get property of non-object
To fix that you can use Auth::id() which will return the ID of the logged in user or null otherwise, but you'll avoid the exception.

Related

Lavavel how to debug local.ERROR: Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent()

i am a laravel noob who has inherited an application
I have this problem that I am debugging. The user gets in a state of infinite loops or gets the error
[2022-05-05 05:01:48] local.ERROR: Argument 1 passed to Symfony\Component\HttpFoundation\Response::setContent() must be of the type string or null, object given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Http/Response.php on line 65 {"userId":11794,"exception":"[object] (TypeError(code: 0): Argument 1 passed to Symfony\\Component\\HttpFoundation\\Response::setContent() must be of the type string or null, object given, called in /var/www/html/vendor/laravel/framework/src/Illuminate/Http/Response.php on line 65 at /var/www/html/vendor/symfony/http-foundation/Response.php:412) [stacktrace]
Where this is happening is in the
HomeController extends FrontController -> index()
when this code is called
return redirect('login');
I can fix the issue , by deleting all the users cookies via dev tools of the browser.
Would love some suggestions how to debug/fix this issue,
Thanks for any help
I had the same error when I called a logout function, and by going to the logout function, reading the code line by line I fixed the issue by removing a "return" that was useless.
Below the logout function :
public function logout(Request $request)
{
$token = $request->header('Authorization');
***return*** JWTAuth::parseToken()->invalidate($token); //remove return
auth()->logout();
return response()->json(['message' => 'User successfully logged out.']);
}

How to Catch a "Trying to get property of non-object Error" in Laravel

How can I find the culprit of the following error in Laravel?
Trying to get property of a non-object Error
This is most probably coming from calling a method\property on a null object. So to fail early, you should use Model::firstOrFail(); or Model::findOrFail(ID);.
Other than that a null check can do it before you use, but it gets ugly if you have many null checks in your code.
try {} catch (\Exception $e) {} is also a way to catch an exception and handle it manually, but doing this in many places is again a lot of work.
What I do is use a ternary operation on the model before accessing properties of that model like so
$model = Model::find($id); $model ? $name = $model->name : null;
with this you can always be rest assured that a fatal throwable error would not be thrown if the model is not found. This also means you have to check if the variable name is not null before working with it like so if(!is_null($name) { //do your stuff here}

Laravel: Function name must be a string

I'm currently working on a project. It was all working just fine until i tried to migrate some tables that I edited. I got this error:
[Symfony\Component\Debug\Exception\FatalThrowableError]
Function name must be a string
Since I doesn't directly show me where the error is, I couldn't find it. Last things I changed before I tried to migrate tables:
Migrations
Laravel colletive/html forms
Store method in my controller
As I know, migrations and forms shouldn't be a problem with this error, so here's my controller code:
public function store(Request $request)
{
$user = Auth::user();
$input = $request->all();
if ($file = $request->file('photo_id')){
$name = time().$file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file'=>$name]);
$input['photo_id'] = $photo->id;
}
$user->posts()->create($input);
return redirect('/userPanel');
}
If the error isn't even in a controller code, where could it be. Any help appreciated.
I have found out it was because of a very silly mistake, i was calling a variable as a function...
$ownedMacs = intval($data()['owned_mac']);
Changed to
$ownedMacs = intval($data['owned_mac']);
This error message usually appears when we are doing something real stupid! :)
Same issue in Laravel can solve
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR)
Function name must be a string
When you checked on storage/logs/laravel.log
local.ERROR: Function name must be a string {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Function name must be a string at E:\\Project\\workspace\\turttyKidsProject\\app\\Http\\Controllers\\SiteContactController.php:52)
[stacktrace]
Solution
Data field requesting another format but you are trying to save an object.
$objectSave= new ObjectClass;
$objectSave->feild_db = $request->post('request_name');
Check whether you access request with your form submit method. it may be POST or GET

Having trouble with Model Bind - Laravel Breadcrumbs

Having trouble with Model Bind on davejamesmiller/laravel-breadcrumbs.
I'll try to be brief, but if you need more data just ask =D
This is my controller/action signature:
public function edit(Request $request, Vertical $vertical, UserMacro $macro)
And this is my BC for the corresponding route:
Breadcrumbs::register('macro-edit', function (Generator $breadcrumbs, $vertical, $macro) {
$breadcrumbs->parent('macro-index');
$breadcrumbs->push($macro->name, route('macro-edit', [$vertical->_id, $macro]));
});
I'm getting the string ID on $vertical and $macro, breaking on $macro->name. If I add Hints as the action have I get aType error.
Trying to get property of non-object (View: /.../resources/views/layouts/app.blade.php) (View: /.../resources/views/layouts/app.blade.php)
Type error: Argument 2 passed to DaveJamesMiller\Breadcrumbs\BreadcrumbsServiceProvider::{closure}() must be an instance of App\Vertical, string given, called in /.../vendor/davejamesmiller/laravel-breadcrumbs/src/BreadcrumbsGenerator.php on line 68 (View: /.../resources/views/layouts/app.blade.php) (View: /.../resources/views/layouts/app.blade.php)
I didn't analyze core code of library, so i don't know why controllers work, but breadcrumbs don't. Recipe to working model binding is use proper route naming convention.
Breadcrumbs::for('messages.show', function($trail, \App\Models\MassMessage $massMessage) {
$trail->parent('Index');
$trail->push('Show', route('messages.show', $massMessage));
});
Route::get('messages/{massMessage}', 'MessageController#show')->name('messages.show');
// error (controllers are fine)
Route::get('mass-mmessages/{massMessage}', 'MessageController#show')->name('messages.show');
// works both
The same problem is with resource route.
edit:
I was wrong. Controller also doesn't work. It not raise error but it pass empty Eloquent object. In my case i needed to change $massMessage variable's name into $message in both places and works fine, now.

Trying to get property of non-object error occurs in my controller

Was trying to call orders made by a particular user
from my database but get error from my controller reporting from controller..
Public function getYourOrders {
$order = Order::where('user_id','=',Auth::user()->id)->get();
return View::make('orders.show')->with('order',$order);
}
This is where the errorexception is reporting from
If you don't have a logged in user, Auth::user()->id would give you that error.
If you work with framework version 4.1.26+ don't use Auth::user()->id to retrieve user's id.
Instead use id method:
Auth::id();
it will take care of returning null if there's no logged in user and it will not execute unnecessary DB query (when using DB driver)

Resources