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

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

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>

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

Putting specific arrays values into a Laravel view table

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

Laravel 5 and Bootgrid Pagination

I'm working with Laravel 5 and Bootgrid Pagination. I'm planning to use it later so I'm learning it and playing around with it but I can't make it work. In my browser console I get
Uncaught TypeError: Cannot read property 'length' of undefined
I don't know if it is the data format that I'm passing.
Here's the html
<table id="grid-data" class="table table-condensed table-hover table-striped" data-toggle="bootgrid" data-ajax="true" data-url="api/deliverytracker">
<thead>
<tr>
<th data-column-id="id" data-identifier="true">ID</th>
<th data-column-id="sender">Sender</th>
<th data-column-id="received">Recieved</th>
</tr>
</thead>
</table>
in my route for api/deliverytracker
Route::any('api/deliverytracker', 'DeliveryTrackerController#deliveryIndexApi');
Then my function in my DeliveryTrackerController
public function deliveryIndexApi()
{
$data = array(
array('id' => '1', 'sender' => '123#test.de', 'received' => '2014-05-30T22:15:00'),
array('id' => '2', 'sender' => '123#test.de', 'received' => '2014-05-30T22:15:00'),
);
return json_encode($data);
}
Did I missed something? I tried to console log my $data which turns out
[{"id":"1","sender":"123#test.de","received":"2014-05-30T22:15:00"},{"id":"2","sender":"123#test.de","received":"2014-05-30T22:15:00"}]
Thanks!
You need to return the JSON correctly .
$data = array(
"current" => 1,
"rowCount" => 10,
"rows" => array(
array('id' => '1', 'sender' => '123#test.de', 'received' => '2014-05-30T22:15:00'),
array('id' => '2', 'sender' => '123#test.de', 'received' => '2014-05-30T22:15:00')
),
"total" => 1123
);
check official documentation http://www.jquery-bootgrid.com/Examples#data

Laravel validate array input

I'm trying to build some custom grid forms which looks like
form.blade.php
<table>
<tr>
<td>
{{ Form::text('name[]', null, array('placeholder' => 'name') }}
</td>
</tr>
<tr>
<td>
{{ Form::text('aerobic[]', null, array('placeholder' => 'aerobic') }}
</td>
</tr>
<tr>
<td>
{{ Form::text('core_test[]', null, array('placeholder' => 'core test') }}
</td>
</tr>
</table>
Validation rules
$validator = Validator::make(Input::all(), array(
'name[]' => 'required|alpha',
'aerobic[]' => 'required|alpha',
'core_test[]' => 'required|alpha'
));
How do I validate the inputs or what other good ways would be to build this?
I get the following errors when I submit the form
htmlentities() expects parameter 1 to be string, array given
(View: /Applications/XAMPP/xamppfiles/htdocs/hp/v1.1/app/views
/files/templates/apa/form.blade.php)
I've also tried this
$validator = Validator::make(Input::all(), array(
'name' => 'required|alpha',
'aerobic' => 'required|alpha',
'core_test' => 'required|alpha'
));
And I get this error from alpha validation rule
preg_match() expects parameter 2 to be string, array given
I've spend a lot of time trying to figure out how to solve this problem...Laravel does not expect a text input to be an array. so you either use plain html for your array inputs, or use custom macros to create your own form class(I assume you're using LaravelCollective).
Take off the [] in the name of each of your inputs. PHP is interpreting those inputs as arrays instead of strings.
Example:
{{ Form::text('name', null, array('placeholder' => 'Name')) }}

Resources