How to get key of the item in laravel collection? - laravel

I pass a collection to the blade templating engine and in there I iterate over it. I want to display items position in the array. I thought of using items key, how do I extract it from the collections items?

No need to overcomplicate things.
// in your controller
return view()->with('collection', $collection);
// in your view
#foreach($collection as $index => $item)
{{ $index }}
#endforeach

Related

How to get all data except last query?

I have this foreach I need to get all data except last one that I current add it
my foreach :
#foreach ($user->projects->sortByDesc('id')->except() as $porject)
// my data
#endforeach
projects is relation between user and projects table
You can use pop() collection method that removes the last item. I would do it in the controller and share the projects with the view.
$projects = $user->projects()->orderBy('id')->get();
$projects->pop();
return view('view', compact('user', 'projects'))
Going from your code you could use take(n):
#foreach ($user->projects->sortByDesc('id')->take($user->projects->count() - 1) as $porject)
// my data
#endforeach
or you could use $loop->last and just render when it's not the last item:
#foreach ($user->projects->sortByDesc('id') as $porject)
#if (! $loop->last)
// my data
#endif
#endforeach
or you could use pop() (as #mrhnn suggested) with tap():
#foreach (tap($user->projects->sortByDesc('id'))->pop() as $porject)
// my data
#endforeach

Only return one row in foreach

I'm starting with Laravel and I'm having trouble getting the results of a query on the laravel blade.
From a list obtained through a query to MySQL 'mysql', I want to check the name it has in another table of another 'tienda' database.
Everything is fine, but it only returns the last value of the second query, it does not return all the values ​​of the $ products query with its corresponding name obtained in $ products_name.
Controller
$productos = [
'id' => $id
];
$products = DB::connection('mysql')
->SELECT("SELECT * FROM promociones_product WHERE id_promo = $id", $productos);
foreach ($products as $product)
{
$products_name = collect(DB::connection('tienda')
->table('ps_product_lang')
->where('id_product', $product->id_product)
->get(['name', 'id_product']));
}
return view('promociones-products')->with('promo', $products_name);
Blade
#foreach($promo as $product)
<tr>
<td>{{ $product->id_product }}</td>
<td>{{ $product->name }}</td>
</tr>
#endforeach
I need to make a query against the 'mysql' database and, with those results, consult its name in another database, and all the values ​​are printed on the screen.
So there are a couple of issues with the code you provided.
To start with, in your loop you are creating a new collection called 'products_name' on each loop which keeps overwriting itself.
There are lots of ways of approaching this however how I would do it is below:
$promo = []; // Initialise a new array called promo
foreach ($products as $product)
{
// Append the collection to the new array
$promo[] = collect(DB::connection('tienda')
->table('ps_product_lang')
->where('id_product', $product->id_product)
->get(['name', 'id_product']));
}
Now you have an array with all of the products in collections.
Now the loop to get that data should work.
You can then return the data to the view using a couple of methods, my preferred method is indeed compact() seen below:
return view('promociones-products', compact('promo'));
What compact() will do is grab any variable names mentioned in the view and pass it through to the view. This compact will pass the $promo variable to the view.

Laravel array shows as null before data array

I have a user that has many properties. This is user should also be able tp view the offers bet on his properties.
So have the relationship set.
User.php
public function properties(){
return $this->hasMany('App\Property');
}
Property.php
public function offers(){
return $this->hasMany('App\Offer');
}
Then in my controller this is what I have:
public function my_offers(){
$properties = Property::whereUserId(Auth::id())->get();
return view('pages.seller.offers.index', compact('properties'));
}
Then I go to my views like this:
#if($properties)
<ul>
#foreach($properties as $property)
<li>{{$property->offers->offer_message}}</li>
#endforeach
</ul>
#endif
When I view the page I see the below error:
Property [offer_message] does not exist on this collection instance.
But this property exists in my table.
If I change my list item to the one below I can see the array:
<li>{{$property->offers}}</li>
I also see that before and after the array with the data, there are two empty arrays as the image shows below:
Is there anything that I didn't correctly?
If not all the properties have offers, then you should check that before the <li>, besides that, offers is a collection, you need to loop through it, that's why you get the error.
#if($properties)
#php ($i = 1)
<ul>
#foreach($properties as $property)
#if ($property->offers)
#foreach ($property->offers as $offer)
<li>Offer {{ $i++ }}: {{$offer->offer_message}}</li>
#endforeach
#endif
#endforeach
</ul>
#endif
If you want to get only de properties that have offers (Querying Relationship Existence):
$properties = Property::whereUserId(Auth::id())->has('offers')->get();
And you should probably eager load that relationship:
$properties = Property::whereUserId(Auth::id())->has('offers')->with('offers')->get();

How do I parse this json data in view blade? Output [{"...":...}]

I am trying to display the maximum value of an attribute in a table
my controller
$member = DB::table('member')
->select(DB::raw('MAX(code) as code'))
->where('status', '=', "No")->get();
return view('member.index', compact('member'));
Currently this is my view
{{ $member }}
And this is the output
[{"code":14101234}]
I wanted to display something like this
14101234
I've tried using json_decode but the result remains.
You receive a collection there, so you will have to do
#foreach($member as $item)
{!! $item->code !!}
#endforeach
Since $member is a array of object you are getting in view.
So you can fetch a object key by -> operator. you can fetch code like this. since you are doing ->get(), so it will return array of object.
#foreach($member as $m)
{{ $m->code }}
#endforeach
$member is a collection object.You can iterate through it to get the value in your view.
example: (in view.blade.php)
#foreach($member as $individual)
{{$individual->code}}
#endforeach
this would give you the value as you want

Assigning a variable to each row from a Get query

In my controller, I'm selecting all rows from a table, lets call it Users.
$users = User::get();
Let's say I want to assign a variable to each row from the Users table, that determines how old they were 10 years ago
I'm assuming I have to use a foreach
foreach ($users as $user) {
$decadeAgo = $user->age - 10;
}
Now in my blade, how can I display each user row, while also displaying the $decadeAgo variable?
try this as official laravel suggestion for blade templates:
#foreach ($users as $user)
<p>{{ $user->age - 10 }}</p>
#endforeach
You can iterate over the results and address each object by reference:
foreach ($users as &$user) {
$user->decadeAgo = $user->age - 10;
}
Then, in your blade template you will have access to the element you created on the $user object.
{{ $user->decadeAgo }}

Resources