Get id of collection in foreach - laravel

I'm trying to get the ID of the share, but, I'm do a foreach in links, look:
#foreach($user->getRelation('shares')->pluck('links') as $link)
{{ $link->first()->title }} //works
{{ //get the ID, of the current share }}
#endforeach
How can I do it?
dd($user->shares);
Collection {#338 ▼
#items: array:3 [▼
0 => Share {#343 ▼
#attributes: array:6 [▼
"id" => 7
"link_id" => 3
"user_id" => 1
"shared_in" => null
"content" => "testetste"
"created_at" => "2018-02-02 15:46:13"
]
#relations: array:1 [▼
"links" => Collection {#349 ▶}
]
}
1 => Share {#344 ▶}
2 => Share {#345 ▶}
]
}

You can specify id as the second parameter for pluck() method:
#foreach($user->getRelation('shares')->pluck('links', 'id') as $id => $link)
{{ $link->first()->title }}
{{ $id }}
#endforeach

In this instance, your shares? are already shared with the view in their entirety and so plucking the links and ids doesn't really save you much performance meaning this loop is unnecessarily complicated.
#foreach($user->getRelation('shares') as $share)
{{ $share->links->first()->title }}
{{ $share->id }}
#endforeach
If however, all you want to use in this view instance is the link and id, then I would recommend modifying your query in the controller to reduce the size of the overall collection being sent to your view instance.

Related

I have a collection of objects in laravel. When I try to access it in blade it shows "Attempt to read property "year_month" on array"

^ Illuminate\Support\Collection {#1471 ▼
#items: array:9 [▼
0 => {#1490 ▼
+"year_month": "2022-01"
}
1 => {#1452 ▼
+"year_month": "2022-02"
}
2 => {#526 ▼
+"year_month": "2022-03"
}
3 => {#1453 ▼
+"year_month": "2022-04"
}
4 => {#1457 ▼
+"year_month": "2022-05"
}
5 => {#1458 ▼
+"year_month": "2022-06"
}
6 => {#1461 ▼
+"year_month": "2022-07"
}
7 => {#1463 ▼
+"year_month": "2022-08"
}
8 => {#1460 ▼
+"year_month": "2022-09"
}
]
#escapeWhenCastingToString: false
}
This is my collection. And I try to access it in Blade as
#if(!empty($monthYears))
<div class="pt-2 pb-2 carousel">
#foreach($monthYears as $monthYear)
<div wire:click="changePeriod('{{$monthYear->year_month}}')" class="text-gray-700 text-base mx-4 cursor-pointer carousel-cell #if($loop->index == count($monthYears)-2) is-clicked #endif">
{{date("m/y", strtotime($monthYear->year_month))}}
</div>
#endforeach
</div>
#endif
On the first load it loads without any issue. But when I click on any events of livewire components it shows "Attempt to read property "year_month" on array".
Here's my livewire component
public Collection $monthYears;
public function mount()
{
$this->monthYears = DB::table('table_name')->orderBy('year_month', 'asc')->groupBy('year_month')->get('year_month');
}
Livewire does not hydrate stdClass properties. They will be converted to array structure.
Note the supported types.

This collection can't be displayed on the blade

I have function to export PDF .
this is have more than 1 collection data on this 1 view . like this
public function PDF(Request $request,$id){
$users = User::findOrFail($id);
$pendidikan = Data_riwayat_pendidikan::where('user_id',$id)->get();
$pdf = PDF::loadView('admin.pdf',['users' => $users,'pendidikan'=>$pendidikan]);
return $pdf->stream('Profile.pdf')->header('Content-Type','application/pdf');
}
I can displayed USERS data , like this {{ $users->nama}}
it's show normally but . I try this {{ $pendidikan->jenjang}} it's have error:
Property [jenjang] does not exist on this collection instance. (View: C:\xampp\htdocs\project\resources\views\admin\pdf.blade.php)
I try dd($pendidikan); and show like this:
Collection {#340 ▼
#items: array:1 [▼
0 => Data_riwayat_pendidikan {#345 ▼
#table: "data_riwayat_pendidikan"
#guarded: []
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:9 [▼
"id" => 1
"user_id" => 14
"jenjang" => "PERGURUAN TINGGI"
"nama_tempat" => "Universitas blablabla"
"jurusan" => "Rekam Medis"
"lulus_tahun" => "2000"
"gelar" => "gelar"
"created_at" => "2019-07-31 08:52:30"
"updated_at" => "2019-07-31 08:52:30"
]
#original: array:9 [▶]
it's can showed at die dump . how can I fix it?
$users is a single object. so you can access its properties like that.
But $pendidikan is a collection. not a single object. so you have to loop through it.
Possible solution
if you are doing this on a blade file.
#foreach($pendidikan as $item)
{{ $item->jenjang }}
#endforeach
you can try this
#if(isset($pendidikan))
<script>
var dataJson = JSON.parse("{!!$pendidikan!!}");
</script>
#endif
or
{!!$ pendidikan-> jenjang!!}
laravel document
Displaying Unescaped Data
By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:
Hello, {!! $name !!}.
Be very careful when echoing content that is supplied by users of your application. Always use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.

Laravel old() function not working --- flash dose not work (stoped working!!)

I'm trying to use old() in Laravel but it doesn't work.
In my controller:
dd(back()->withInput());
this is the session result
#session: Store {#364 ▼
#id: "dyNmtFJVQCQmcCob4SPYEBzWHJ6TJeM9X0mzWWu7"
#name: "laravel_session"
#attributes: array:6 [▼
"_token" => "NVJATvxuHRlGbAC1jUEIjS6gbLQQEWPIIV41fLYd"
"url" => []
"_previous" => array:1 [▼
"url" => "http://localhost:8000/units/23/rents/create"
]
"_flash" => array:2 [▼
"old" => []
"new" => array:1 [▼
0 => "_old_input"
]
]
"login_web_59ba36addc2b2f9401580f014c7f58ea4e30989d" => 1
"_old_input" => array:5 [▼
"_token" => "NVJATvxuHRlGbAC1jUEIjS6gbLQQEWPIIV41fLYd"
"contract_id" => "20"
"unit_id" => "23"
"amount_paid" => "1"
"submit" => "submit"
]
]
#handler: FileSessionHandler {#363 ▶}
#started: true
value="{{ old('amount_paid')}}" I would get empty field
value="{{ old('amount_paid','test') }}" I would get 'test' in the field
I'm using Laravel 5.6
EDIT
to clarify the above code it to debug
this is my original code
controller
return back()->withInput();
view
<div class="form-group">
<label> amount paid </label>
<input type="float" class="form-control" name="amount_paid" value="{{ old('amount_paid')}}" required>
</div>
adding the method that handle the request
public function store(Request $request)
{
// updating the amount paid
$rent = new Rent;
$rent->amount_paid = $request->amount_paid;
try {
$rent->save();
} catch (\Illuminate\Database\QueryException $e) {
//return to the form and populate it
return back()->withInput();
}
return redirect('units/'.$request->unit_id);
** update **
It appear that session->flash is not working.
I tried a new installation of laravel and it is working fine
The problem was related to session it self.
I have 2
\Illuminate\Session\Middleware\StartSession::class,
one in middleware and another in $middlewareGroups[web].
this was a result of following a tutorial in youtube months ago to implement localisation :(

Filling selects with appropriate data

I am having issues trying to figure something out. I pass my view an array of data which takes the following form
array:4 [▼
"data" => array:2 [▼
2015 => array:2 [▼
"english" => array:1 [▼
"chips" => array:1 [▼
0 => "img1.png"
]
]
"french" => array:1 [▼
"mussles" => array:1 [▼
0 => "img1.png"
]
]
]
2016 => array:2 [▼
"indian" => array:1 [▼
"madras" => array:1 [▼
0 => "img1.png"
]
]
"italien" => array:1 [▼
"pasta" => array:1 [▼
0 => "img1.png"
]
]
]
]
]
This stucture is obtained from scanning a directory structure, but it should be pretty consistent. The overall structure is
Year>Country>Dish>Images
I need to somehow display this data within select options. So year is pretty straight forward, I can do this
<select id="yearSelection" class="selectpicker form-control">
#foreach($fileData["data"] as $year => $country)
<option value="{{ $year }}">{{ $year }}</option>
#endforeach
</select>
Here is my problem. So the above select will display 2015 and 2016. I then have a second select input
<select id="countrySelection" class="selectpicker form-control">
<option value=""></option>
</select>
Now depending on what year they select is going to determine what this select should display. So if they select 2015, this select should display english and french.
How can I populate my select options based on previous selections?
You will need to use AJAX to accomplish this in a smooth-looking way.
Or you could refresh when your selected option changes and send the selected year (and other data) using GET parameters.
Then you can just pass your data on to the view depending on your GET parameters.
This should point you to the direction you want to go.

Laravel: How can I use Group By within my view?

I am trying to get all students, then group them by graduation year. Within my view, I want to have a headline of the year:
<h2>2016</h2>
<ul>
<li>Last, First</li>
...
</ul>
<h2>2017</h2>
<ul>
<li>Last, First</li>
...
</ul>
I believe I am close, but not sure of the "Laravel way". The data looks good - as in, the query is getting/grouping correctly, I think my struggle is understanding how to loop through the collection.
MyController.php
public function index()
{
$students = Student::all()->groupBy('grad_year');
return view('student.index', compact('students'));
}
In my view I can see I am getting this:
MyView.blade.php
{{dd($students)}}
Collection {#178 ▼
#items: array:2 [▼
2016 => Collection {#173 ▼
#items: array:3 [▼
0 => Student {#180 ▶}
1 => Student {#181 ▶}
2 => Student {#182 ▶}
]
}
2017 => Collection {#172 ▶}
]
}
SOLUTION
Here is what my view looks like to get the output I wanted.
MyView.blade.php
#foreach ($collection as $year => $students)
<p>{{$year}}</p>
<ul class="list-unstyled">
#foreach($students as $student)
<li>{{ $student->last_name }}, {{ $student->first_name }}</li>
#endforeach
</ul>
#endforeach
something like:
$studentsByYear = $students;
foreach ($studentsByYear as $year => $students) {
echo "<h2>$year</h2>";
echo "<ul>";
foreach ($students as $student) {
echo "<li>".$student->name."</li>";
}
echo "</ul>";
}

Resources