Loop through object within an array Laravel


Loop through object within an array Laravel



I'm trying to loop through an object in an array in Laravel.



I made a foreach to loop through my $request->newTags what is an object and I just return the key. my goal is to access each tag_name in my request object what has an array with the multiple indexes what contain the tag_name.


foreach


$request->newTags


tag_name


request object


array


tag_name


foreach ($request->newTags as $tag) {
return $tag;
}



and i get my response
enter image description here



how can I access each tag_name?




2 Answers
2



Try this


foreach ($request->newTags as $tag) {
return $tag.tag_name;
}





Do you mean $tag->tag_name ?
– Yosef
Jul 1 at 7:11


$tag->tag_name





becuase tag.tag_name return an error
– Yosef
Jul 1 at 7:11


tag.tag_name





@Yosef Yep try that. If that doesn't work try $tag['tag_name']
– ST415
Jul 1 at 7:12





both don't work doing $tag->tag_name will return trying to get property of non-object and doing $tag['tag_name'] will return undefined index: tag_name
– Yosef
Jul 1 at 7:15


$tag->tag_name


trying to get property of non-object


$tag['tag_name']


undefined index: tag_name





Hmm try using pluck laracasts.com/discuss/channels/laravel/…
– ST415
Jul 1 at 7:19


pluck



You are using return on each iteration which will exit the function first ooff.But it doesnt matter because newTags only contains one item, which is an array. So it sounds like you have an object attribute $tags->newtags which is an array containing an array. I bet that this will not throw an error for example:



echo $tags[0]["tag_name"];


echo $tags[0]["tag_name"];



Your problem is nesting.





Yea I realized the mistake with return
– Yosef
Jul 1 at 16:51





Can you access your key if you go through the index of $tags? I would probably cast all to an array if $tags is mixed for simplicity btw.
– OneLiner
Jul 1 at 16:54







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Rothschild family

Cinema of Italy