How to over ride property value in laravel collection - php

Hi I am trying to over ride the property value using a foreach loop.
Here is what I am trying
$runningLeagues = $this->getLeagueListing('running', $clubIds);
// chanage city
foreach($runningLeagues as $d){
$d->club->city = $d->city;
}
return $runningLeagues;
But if I just return from the loop I get the correct result. So the below code works.
foreach($runningLeagues as $d){
$d->club->city = $d->city;
return $d; // it shows the overridden city. It works.
}
I have city property inside club object and outside object as well. I want to change the city inside the club object from the outside city property value.
It keeps the values same. It doesn't change.
Update
it seems it updates with the last item. So if last properties city is 'ss' it will add 'ss' in all the properties.
Any idea whats happening?
Thank you.

Try this:
First. Laravel collection each() method:
$runningLeagues->each(function ($d) {
$d->club->city = $d->city;
});
Second. By collection index:
foreach($runningLeagues as $k => $d) {
$runningLeagues[$k]->club->city = $d->city;
}

Related

Laravel. After call toArray(), the value in attribute property is changed

I want to get address data from customer table.
But my address data includes country, city and address.
Therefore I want to make address field to country, city and address three fields.
The following is my code
$result = Customer::select('customers.address AS country', 'customers.address AS city', 'customers.address')->get();
dump($result[0]); // First result
$temp = $result->toArray();
dd($temp[0]); // Second result
The following is my questions:
Why is country and city changed in attribute property? I didn't do anything.
It is magic. I change [country] to [countrys] and [city] to [citys].
The following is my new code
$result = Customer::select('customers.address AS countrys', 'customers.address AS citys', 'customers.address')->get();
dump($result[0]);
$temp = $result->toArray();
dd($temp[0]);
The countrys and citys didn't change in attribute property anymore.
The output picture:
Can anyone tall me why? It's really strange.
As per Laravel Documenation:
The toArray method converts the collection into a plain PHP array. If the collection's values are Eloquent models, the models will also be converted to arrays
Aslo
toArray also converts all of the collection's nested objects that are
an instance of Arrayable to an array. If you want to get the raw
underlying array, use the all method instead.
Laravel -> Collection -> toArray()
The following is my code to resolve my question [Why is country and city changed in attribute property?]
// Add the following code to Customer model
public function setCountryAttribute($value)
{
$this->attributes['country'] = $value;
}
public function getCountryAttribute()
{
return $this->attributes['country'];
}
public function setCityAttribute($value)
{
$this->attributes['city'] = $value;
}
public function getCityAttribute()
{
return $this->attributes['city'];
}

Foreach loop seems to destroy the array in Laravel / PHP 7

I have a simple CRUD item called Filters. In here each filter is assigned to a category with a foreign key. What I am trying to do is loop through each foregin key to get the category name rather than id to display to the user.
I get all filters first and performed a die/dump to check all results were there and they are.
When trying to assign the category name to the correct array item I get this error:
"Indirect modification of overloaded element of App\Filter has no effect"
So to check what's happening I have die/dumped inside the foreach loop and the exact same data has now disappeared. Even if I just put a foreach loop in with no modiifcaiton of the original array, when I pass this back to the view it has been unset.
AM I being very naive and not realising something this foreach loop does that destroys this data???
I have copied my code below and commented where the dd works and doesn't;
public function show()
{
$filter = [];
$filter['filters'] = Filter::all();
//dd($filter['filters']); --this works fine here
foreach($filter['filters'] AS $key => $filter){
//dd($filter['filters']); --this returns null here
$category = Category::where('id', $filter->category)->first();
$filter['filters'][$key]->category = $category->category;
}
return view('admin.crud.filters.index')->with('filter', $filter);
}
Don't re-initialize a variable or different data-type with same name
Try to change the $filter to something else in foreach loop. Because you already have an array with same name.
Do something like:
foreach($filter['filters'] AS $key => $f){...}

why foreach print just one value in laravel?

I have a method:
public function winnerDetails()
{
$winners = DB::table('winners')->get();
//dd($winners);
foreach ($winners as $winner) {
$qrMainId = $winner->qrdetails_id;
}
dd($qrMainId);
}
dd($winners); returns to value of array but when i use foreach its returns one value. How can i get who value returns with foreach loop?
dd($winners) output:
and dd($qrMainId); return one value 44. But it should return another value of array 35; Thanks in advance.
To get array of ID's use
foreach ($winners as $winner) {
$qrMainId[]= $winner->qrdetails_id;
For just value use
$qrMainId='';
foreach ($winners as $winner) {
$qrMainId.= $winner->qrdetails_id;
If you want to accomplish this task in a Laravel way use the pluck method to map the array for the key that you want
<?php
public function winnerDetails()
{
$winnersId = DB::table('winners')->get()->pluck('qrdetails_id');
dd($winnersId);
}
I think you are not leveraging the power of Laravel here. Obviously, I don't know what you are trying to do but here are some pointers.
You should probably be making a model for the winners table now models in Laravel return Collections as does the DB facade you are using now. Now the Collection class contains alot of usefull helpers like pluck
At this point it becomes as easy as Winner::all()->pluck('id') and you got yourself an array of id's.
And if you would like to get them comma seperated or anything like that you can use the implode
And you would get Winner::all()->implode('id',',');
$qrMainId is a variable not an array.
It is modified in the foreach during every loop.
So your code has always the last element of the array.
Use an array to collect values like
$qrMainId[] = $winner->qrdetails_id;
or sql select directly the field you want.

Laravel model data foreach

I have the following line $totalRequests = \App\LoanRequest::all(); which returns all records, Along a model Applicant which have One to Many relation with LoanRequest.
So i can access applicants data with $totalRequests[0]->applicant->region for with foreach().
Question :
Now i want all the distinct regions in the Applicant or table applicants from the LoanRequest::all() model and want to push those regions to an array which then i can pass to a view.
What i am trying :
$totalRequests = \App\LoanRequest::all();
foreach($totalRequests as $applicant){
$filterMeta = [];
array_push($applicant->aplicant->region, $filterMeta);
}
It throws:
Indirect modification of overloaded property App\Applicant::$region has no effect
If you want to push the region to the array, you're using the wrong argument order. Also, shouldn't you be initalising the filter meta array outside of the loop?
$totalRequests = \App\LoanRequest::all();
$filterMeta = [];
foreach($totalRequests as $applicant){
array_push($filterMeta, $applicant->aplicant->region);
}

Laravel error "Trying to get property of non-object" when inside an if() condition

It's strange, I can access the property before the if statement, and if I change the if condition to something else, I can accessible the property inside the if statement as well. But trying to access the property inside the if condition throws an error:
$market_ids = [];
$state->cities->each(function($city) use (&$market_ids)
{
dd($city->market->id); // <-Accessible here
if (!in_array($city->market->id, $market_ids)){ // Error: Trying to get property of non-object
dd($city->market->id); // Accessible here
$market_ids[] = $city->market->id;
}
});
Error: Trying to get property of non-object
Anyone run into this before?
I think, you should make sure that for each of your cities your relation doesn't return null:
$market_ids = [];
$state->cities->each(function($city) use (&$market_ids)
{
if ($city->market === null) {
echo " null market for ".$city->name."<br />";
continue;
}
if (!in_array($city->market->id, $market_ids)){
$market_ids[] = $city->market->id;
}
});
As you used dd you checked it for first record and it doesn't mean that for 2nd or 3rd or later rows there's corresponding market object. For example you have 100 cities and 99 nine of them have market and one of them doesn't. You will get the error you asked because for one of them you don't have market so you cannot ask for market id.
So to make it clear this error is rather not connected to if or in_array, because if you use:
$market_ids = [];
$state->cities->each(function($city) use (&$market_ids)
{
echo $city->market->id; // not dd but simply echo
});
you will probably also get the same error.
Trying to get property of non-object
means the source $city->market not an object in some cases, or check this edit:
$market_ids = [];
$state->cities->each(function($city) use (&$market_ids)
{
$id = $city->market->id;
dd($id);
if ( ! in_array($id, $market_ids) ){
dd($id);
$market_ids[] = $id;
}
});

Categories