Putting specific arrays values into a Laravel view table - laravel

I have this nested array under the variable $audits which I hand over to a Laravel 5.8 view:
array:4 [▼
0 => array:3 [▼
"action" => "Case initiated by:"
"user" => "Doe, Jane"
"timestamp" => Carbon #1558353758 {#419 ▶}
]
1 => array:3 [▼
"action" => "New head mediator:"
"user" => "Doe, Jane"
"timestamp" => Carbon #1558353758 {#430 ▶}
]
2 => array:3 [▼
"action" => "Case closed by:"
"user" => "Doe, Jane"
"timestamp" => Carbon #1558353787 {#467 ▶}
]
3 => array:3 [▼
"action" => "Case re-opened by:"
"user" => "Doe, Jane"
"timestamp" => Carbon #1558353791 {#474 ▶}
]
]
My goal is to fill a table in the view to get the following output:
Action User Date/time (UTC)
-------------------------------------------------------
Case initiated by: Doe, Jane 2019-05-20 12:02:38
New head mediator: Doe, Jane 2019-05-20 12:02:38
Case closed by: Doe, Jane 2019-05-20 12:03:07
Case re-opened by: Doe, Jane 2019-05-20 12:03:11
To achieve that, I had hoped to be able to loop through like this:
<table>
<th>Action</th>
<th>User</th>
<th>Date/time (UTC)</th>
#foreach ($audits as $audit)
#foreach ($audit as $value)
<tr>
<td>{{ $value['action'] }}</td>
<td>{{ $value['user'] }}</td>
<td>{{ $value['timestamp'] }}</td>
</tr>
#endforeach
#endforeach
</table>
However, this will give me error messages since the view doesn't seem to be able to retrieve such specific values from arrays as it can only handle strings.
So, I tried to transform the array into objects, use JSON encoding etc. but to no avail.
The way the array gets constructed in the controller is like this (maybe somebody can point me in a direction how to make a proper collection or object so that it can be handled better by the view):
public function show(Project $project)
{
$audits_raw= $project->audits;
foreach ($audits_raw as $audit_raw) {
foreach ($audit_raw->new_values as $action => $id) {
if ($action == 'initiator_id') {
$actions[] = 'Case initiated by:';
$users[] = $this->userName($id);
$timestamps[] = $audit_raw->updated_at;
} elseif ($action == 'head_mediator_id') {
$actions[] = 'New head mediator:';
$users[] = $this->userName($id);
$timestamps[] = $audit_raw->updated_at;
} elseif ($action == 'marked_for_deletion' && $id == 1) {
$actions[] = 'Case closed by:';
$users[] = $this->userName($audit_raw->user_id);
$timestamps[] = $audit_raw->updated_at;
} elseif ($action == 'marked_for_deletion' && $id == 0) {
$actions[] = 'Case re-opened by:';
$users[] = $this->userName($audit_raw->user_id);
$timestamps[] = $audit_raw->updated_at;
}
}
}
$audits = array_map(function ($action, $user, $timestamp) {
return array_combine(
['action', 'user', 'timestamp'],
[$action, $user, $timestamp]
);
}, $actions, $users, $timestamps);
return view('admin.billing.show', compact('project', 'audits', 'actions'));
}
protected function userName($id)
{
$user = User::where('id', $id)->first();
$username = $user->last_name.', '.$user->first_name;
return $username;
}
Many thanks in advance!

Change the view.
#foreach($audits as $key)
<tr>
<td>{{ $key['action'] }}</td>
<td>{{ $key['user'] }}</td>
<td>{{ Carbon\Carbon::parse($key['timestamp'])->format('Y-m-d H:i:s') }} .
</td>
</tr>
#endforeach

Related

How to pass data collection to mail in Laravel?

How to pass data collection to mail? I don't know the proper term but set of data I guess. I want to display a list of users in my pdf. Every time I use foreach in blade, it fails to send the mail. Ex. I want to display the users John Doe, Jane Doe, Peter Parker from model Signature to my pdf mail. my reference for sending mail with pdf.
In my controller
public function sendEmail(Request $request)
{
$sig = Signature::all();
$users = StudentApplicant::whereIn("id", $request->ids)->get();
foreach ($users as $key => $user) {
$data = [
'studnum' => $user->users->stud_num,
'fname' => $user->users->first_name,
'mname' => $user->users->middle_name,
'lname' => $user->users->last_name,
'gwa' => $user->gwa,
'award' => $user->award_applied,
'award_name' => $user->award->name,
'sy' => $user->school_year
];
$details = ['email' => $user->users->email];
SendEmailJob::dispatch($details, $data, $data['studnum'], $sig);
}
StudentApplicant::whereIn("id", $request->ids)->update(['certificate_status' => 1]);
return response()->json(['success' => 'Send email successfully. Refresh the page']);
}
cert blade file
<table class="table2">
<tr>
#foreach ($sig->take(3) as $item)
<td width="21%">
<b>{{ $item->name }}</b><br>
{{ $item->position }}
</td>
#endforeach
</tr>
</table>
<table class="table2">
<tr>
#foreach ($sig as $item)
#if ($loop->last)
<td>
<b>{{ $item->name }}</b><br>
{{ $item->position }}
</td>
#endif
#endforeach
</tr>
</table>

User Model return null for the user name

I'm trying to display the users name using blade, but Its says null.
This is the controller
public function edit(Project $project)
{
//
$project = Project::findOrFail($project->id);
$assignees = User::with('roles')->get();
return view('projects.edit',['project'=>$project,'assignees'=>$assignees]);
}
When I dd($assignees) all the columns appears including the name column.
#attributes: array:10 [▼
"id" => 4
"name" => "Kitten Moose"
"email" => "kitten#karata.com"
"email_verified_at" => null
"password" => "$2y$10$iG4EZBq13ExGOVIrGNhEQeVvordWc3ibWfYgdaq6x0wqefetqXixe"
"remember_token" => null
"created_at" => "2020-07-03 05:11:56"
"updated_at" => "2020-07-11 09:37:49"
"team_id" => 3
"deleted_at" => null
]
On blade:
<div class="form-group">
<label for="exampleFormControlSelect1">Assignee</label>
<select name="assignee_id" class="js-example-basic-single">
<option value=" ">Select</option>
#foreach($assignees as $assignee)
<option value="{{$assignee->id}}">{{$assignee->name}}</option>
#endforeach
</select>
</div>
Using the blade above, I get {"id":1,"name":null} everything else displays correctly
I'm not sure if this could be caused by the model, but I have this in the user model:
public function assignee()
{
return $this->belongsTo(User::class);
}

How to display eloquent query into view blade?

I am querying a list of staffs from 'itemregistration' table with the eloquent relationship with 'section' table. But I cannot display the information from section table to the view blade.
My controller get the query as follows:
$itemregistrations = Itemregistration::with('section')->get();
When I check the array with:
dd($itemregistrations->toArray());
I get this result:
0 => array:133 [▼
"ItemRegistrationID" => 1
"RegistrationDate" => "2005-12-01"
"SectionID" => 12
"name" => "A SANTESH"
"section" => array:2 [ …2]
]
The section array should contain 'SectionID' and 'sectionname' fields.
If I check with
dd($itemregistration);
it produce
Collection {#1948 ▼
#items: array:1125 [▼
0 => Itemregistration {#1990 ▼
#primaryKey: "ItemRegistrationID"
#hidden: array:1 [ …1]
+timestamps: false
#connection: "mysql"
#table: null
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:133 [ …133]
#original: array:133 [ …133]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [ …1]
#touches: []
#visible: []
#fillable: []
#guarded: array:1 [ …1]
I want to display the result in the blade but failed to fetch the section array value:
#foreach($itemregistrations as $index => $value)
<td>{{ $value->name }}</td>
<td>{{ $value->section->sectionname }}</td>
#endforeach
I also tried:
#foreach($itemregistrations as $index => $value)
<td>{{ $value->name }}</td>
#foreach($value as $section => $val)
<td>{{ $val->sectionname }}</td>
#endforeach
#endforeach
But also failed. The error appears is "Trying to get property of non-object".
I tried to see the values contained in the collection through this code:
#foreach ($itemregistrations as $item)
<tr>
<td>{{ $item }}</td>
<td>{{ $item->section }}</td>
</tr>
#endforeach
And it shows this value in this format:
{"ItemRegistrationID":1,"name":"A Santesh"{"SectionID":12,"sectionname":"E"}}
If I show the result with this:
#foreach ($itemregistrations as $item)
{{ $item->name }}
#endforeach
I can get the name list but to get the sectionname with this
#foreach ($itemregistrations as $item)
<tr>
<td>{{ $item->section->sectionname }}</td>
</tr>
#endforeach
It shows error "Trying to get property of non-object ". I dont understand why I can't get the section values.
My section model:
class Section extends Authenticatable
{
protected $table = 'sections';
protected $primaryKey = 'SectionID';
/**
* Get the user that have agama.
*/
public function itemregistrations()
{
return $this->hasMany('App\Itemregistration', 'SectionID', 'ItemregistrationID');
}
}
Itemregistration model:
class Itemregistration extends Model
{
protected $primaryKey = 'ItemRegistrationID';
/*
* Get all of the owning models.
*/
public function section()
{
return $this->belongsTo('App\Section', 'SectionID');
}
How to get display the query with section array values?
You can do with the following code:
#foreach($itemregistrations as $index => $value)
<td>{{ $value->name }}</td>
#foreach($value->section as $section)
<td>{{ $section->sectionname }}</td>
#endforeach
#endforeach
I assume, that #foreach call toArray() on Collection, so then you should handle your data as named array, so try this:
#foreach($itemregistrations as $index => $value)
<td>{{ $value['name'] }}</td>
#foreach($value['section'] as $section => $val)
<td>{{ $val['sectionname'] }}</td>
#endforeach
#endforeach
Thank you for others' help with my question.
I had configured the right syntax to get to the values of sectionname in section array. I don't know why I can't use -> helper to get to the values. I tried the following syntax and it can fetch the values in blade view.
#foreach ($itemregistrations as $item)
<tr>
<td>{{ $item->name }}</td> //also can <td>{{ $item['name'] }}</td>
<td>{{ $item['section]['sectionname'] }}</td>
</tr>
#endforeach

Laravel - Property [name] does not exist on this collection instance

I am trying to create a Collection and pass it to blade. My PHP code look like this
$collection1 = collect(['name' => 'Alex', 'id' => '1']);
$collection2 = collect(['name' => 'John', 'id' => '2']);
$collection3 = collect(['name' => 'Andy', 'id' => '3']);
$people_col = new Collection();
$people_col->push($collection1);
$people_col->push($collection2);
$people_col->push($collection3);
return view('test',[
'people_col' => $people_col
]);
In my blade I loop through people_col to get properties of items:
#foreach ($people_col as $people)
<tr>
<td>{{ $people->name }}</td>
<td>{{ $people->id }}</td>
</tr>
#endforeach
However I got this error:
Property [name] does not exist on this collection instance
Any idea?
Thanks
You are creating a collection of collections where you should have created a collection of objects instead.
With your current implementation you should be able to get the values using array access method {{ $people['name'] }} or using get method on collection {{ $people->get('name') }}
If you created a collection of objects like below and return it instead of what you are doing now
$people_col = collect([
(object) ['name' => 'Alex', 'id' => '1'],
(object) ['name' => 'John', 'id' => '2'],
(object) ['name' => 'Andy', 'id' => '3']
]);
return view('test', [
'people_col' => $people_col
]);
Then in your view you should be able to access people object like you have done in your code.
#foreach ($people_col as $people)
<tr>
<td>{{ $people->name }}</td>
<td>{{ $people->id }}</td>
</tr>
#endforeach
Try to access to the property name this way: $people['name']
#foreach ($people_col as $people)
<tr>
<td>{{ $people['name'] }}</td>
<td>{{ $people['id'] }}</td>
</tr>
#endforeach

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