Trying to get property 'name' of non-object error in laravel - laravel

here is my function.
public function get(Request $request){
$bike1 = $request->input('bike1');
$bike2 = $request->input('bike2');
//dd($bike1);
return $bike2->name;
}
When i use the dd function, the result is:
"{"id":1,"created_at":"2020-09-16T12:33:25.000000Z","updated_at":"2020-09-16T12:33:25.000000Z","name":"302r","brand":"benelli","price":800000,"displacement":300,"segment":"300cc","power":"28KW#10000 rpm","torque":"27Nm#9000rpm","fuel_delivery_system":"Efi","abs":"1","cooling_system":"Liquid","weight":155} ◀"
But when I try to access the name property(any) i get the error.
Trying to get property 'name' of non-object
What I might be missing?

It looks like $bike1 is a JSON string, before you can access it's attributes you need to decode it.
$bike1 = json_decode($request->input('bike1'));
return $bike1->name
If that doesn't work $bike1 may be an array, not an object, in that case, this should work
return $bike1['name']

you missed that you returned a string, not an object

first decode your json then after get you name
$bike2 = json_decode($request->input('bike2'));
return $bike2->name

You need to decode $bike2 because it's in JSON format, so you can do
$decoded_bike2 = json_decode($request->input('bike2'));
This will return an object
{#1236 ▼
+"id": 1
+"created_at": "2020-09-16T12:33:25.000000Z"
+"updated_at": "2020-09-16T12:33:25.000000Z"
+"name": "302r"
}
you can access name property like
return $decoded_bike2->name;
If you do
$decoded_bike2 = json_decode($request->input('bike2'), true);
This will return an array
array:4 [▼
"id" => 1
"created_at" => "2020-09-16T12:33:25.000000Z"
"updated_at" => "2020-09-16T12:33:25.000000Z"
"name" => "302r"
]
You can access key name like
return $decoded_bike2['name'];
For more details about json_decode() Reference

Related

Laravel String helper returns object

When I do this:
$test = Test::create([
'email' => Str::of($this->email)->trim(),
]);
dd($test->toArray());
I get this:
array:14 [▼
"email" => Illuminate\Support\Stringable {#669 ▼
#value: "test#test.com"
}
]
The problem is that I'm passing $test to an event, and in that event $event->test->email is empty when I for instance send it in a Slack notification. I'm guessing because it's an object and not a string?
I know that I can use PHPs trim(), but I have some more complex Str helpers that I chain which is really helpful. How can I make sure the end result is a string and not an object of Stringable?
Preferably directly when using Str::of($this->email)->trim(), and not for instance doing something like public string $email; in the event because as indicated I use multiple parameters and don't want to convert them all separately.
Try to cast it as string using (string) or __toString() like
$test = Test::create([
'email' => (string)Str::of($this->email)->trim(),
]);
$test = Test::create([
'email' => Str::of($this->email)->trim()->__toString(),
]);

Laravel FirstOrCreate function with null value converts to string

I send a null value for search field, and it converts to string.
using laravel 8. php 7.4
$notification = Notification::firstOrCreate([
'resource' => $notif['resource'],
'topic' => $notif['topic'],
'response' => null
], [some other values]);
returns
#attributes: array:12 [
"resource" => "/item/55359"
"topic" => "item"
"response" => "null" --> like string and not null value
"status_id" => "Pending"
"attempts" => 0
]
thanks
it was a model problem...
the response field saves a json string.. and it was converting the null value to json string.
that was the problem.
i have add this line before
if (is_null($value)) $this->attributes['response'] = $value;
thanks all

Strange Eloquent Behavior: Trying to get property 'name' of non-object while Object exist

I have this function that returns a value in the DB:
public function getMetaValue($key)
I then created a function to read a data in the DB based off of the getMetaValue:
public function getFeatureByMeta($estate, $type)
{
$metaId = (int) $estate->getMetaValue($type);
$feature = Feature::where('id', $metaId)->first();
return $feature->name;
}
If I now return:
$this->getFeatureByMeta($estate, 'stato_immobile')
It throws
Trying to get property 'name' of non-object.
While if I dump-die the same exact thing it dumps the correct result:
dd($this->getFeatureByMeta($estate, 'stato_immobile'));
//Returns "Nuovo / In costruzione" which is the DB data `name` I need
If I take the function getFeatureByMeta and instead of Feature::where('id', $metaId) I hardcode the id value, the above error does not show up and I do get the correct item name:
public function getFeatureByMeta($estate, $type)
{
$feature = Feature::where('id', 54)->first();
return $feature->name;
}
And
public function getFeatureByMeta($estate, $type)
{
$metaId = (int) $estate->getMetaValue($type);
dd($metaId); //Returns 54
}
If I dd($feature) I do get the row I'm talking about:
App\Feature^ {#904
//...
#attributes: array:5 [
"id" => 57
"name" => "Da ristrutturare"
"category" => "stato_immobile"
"created_at" => "2019-09-16 12:15:13"
"updated_at" => "2019-09-16 12:15:13"
]
#original: array:5 [
"id" => 57
"name" => "Da ristrutturare"
"category" => "stato_immobile"
"created_at" => "2019-09-16 12:15:13"
"updated_at" => "2019-09-16 12:15:13"
]
#changes: []
//...
}
What can be causing this?
I made a video to make it more clear: https://streamable.com/5nsq4
For some reason I still don't understand the only solution I found is this:
public function getFeatureByMeta($estate, $type)
{
$feature = Feature::find($estate->getMetaValue($type));
if ($feature) {
return $feature->name;
}
}
Using the if returns the correct name attribute.
If you know why, please comment.

How to access array properties with Laravel Eloquent, if stored in a database?

For example, I have JSON stored in a Row of a database called 'data'
External.php (model) - casting 'data' to an array:
protected $casts = [
'data' => 'array',
];
I can access it using Tinker with this commmand:
$external = App\External::first()->pluck('data');
This returns
Illuminate\Support\Collection {#3384
all: [
[
"id" => 17566616456845,
"name" => "#1008",
"note" => "",
"tags" => "",
"test" => false,
"email" => "katie.jane#example.com",
"phone" => null,
...
..
.
How do I access the "email" or "id" from that collection? How do I modify the tinker eloquent command to get the "id" or "email"?
$external = App\External::all()->pluck('data')->'email'
T_STRING or T_VARIABLE or '{' or '$' on line 1> Exception with message 'Property [email] does not exist on this> PHP Parse error: Syntax error, unexpected T_CONSTANT_ENCAPSED_STRING,
expecting
Getting warmer:
>>> $external = App\External::pluck('data')->get('email')
=> null
pluck() method returns array. So if you want to access 'email' you must use.
$external = App\External::first()->pluck('data');
$email = $external['email']; // katie.jane#example.com
If you are just trying to get the data for one record use the cast attribute as an array:
// one External record
$external = App\External::first();
$email = $external->data['email'];
$id = $external->data['id'];
Try this
$external = collect(App\External::all()->pluck('data'))->pluck('email')->all();
You don't have to use pluck().
if you want to access email from the data of an External.
$email = App\External::first()->data['email'];
UPDATE
to get all the emails.
$emails = App\External::all()
->map(function($external) {
return $external->data['email'];
});

How retrieve element from collection by name?

First, I create collection from array:
$bank_center = collect(array("amount" => null, "mfo" => null, "name" => null));
Then I try to get value by key:
dd($bank_center->name);
Dump is:
Collection {#562 ▼
#items: array:3 [▼
"amount" => null
"mfo" => null
"name" => null
]
}
In your particular case, the following would just work:
$bank_center['name'];
I am not sure why you want to wrap it as an object, but if you still wish to do it, I'd recommend you take a look at Fluent.
$bank_center = new \Illuminate\Support\Fluent(array("amount" => 'test', "mfo" => 'test2', "name" => 'test3'));
dd($bank_center->name); // test3
You should use square brackets to access item from such collection:
$bank_center['name']
To retrieve element by name from collection you can use get method, it returns the item at a given key. If the key does not exist, null is returned:
$collection = collect(['name' => 'bruno', 'framework' => 'laravel']);
$value = $collection->get('name');
// bruno

Resources