How to display eloquent query into view blade? - laravel-5

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

Related

Laravel 9 Relationships Not Returning an Array of Data [duplicate]

This question already has answers here:
Property [title] does not exist on this collection instance
(8 answers)
Closed last month.
I am attempting to build a query that pulls from two tables with a one-to-many relationship. Rather than getting an array of data that exists for the relations, the output of the dd($customer); is:
0 => App\Models\Customer {#1496 ▼
#connection: "mysql"
#table: "customers"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
+preventsLazyLoading: false
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#escapeWhenCastingToString: false
#attributes: array:42 [▶]
#original: array:42 [▶]
#changes: []
#casts: array:1 [▶]
#classCastCache: []
#attributeCastCache: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▼
"xray_machine" => Illuminate\Database\Eloquent\Collection {#1538 …2}
]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#fillable: array:34 [▶]
#guarded: array:1 [▶]
#forceDeleting: false
}
Customer Model
public function xray_machine()
{
return $this->hasMany(Xray_machine::class);
}
Xray_machine Model
public function customer()
{
return $this->belongsTo(Customer::class);
}
Controller
public function epes_scheduled(){
$customers = Customer::with('Xray_machine')->get();
dd($customers);
return view('work_orders/epe_scheduled', compact('customers'));
}
and in the view (by removing the dd() in controller I get this error:
Property [model] does not exist on this collection instance.
The View
#foreach ($customers as $customer)
<tr>
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<div class="ml-4">
<div class="text-sm font-medium text-gray-900">
#if($customer->customer_name) {{$customer->customer_name}} #endif
</div>
</div>
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<div class="ml-4">
<div class="text-sm font-medium text-gray-900">
#if($customer->Xray_machine->model) {{$customer->Xray_machine->model}} #endif
</div>
</div>
</div>
</td>
</tr>
#endforeach
You are in right track and also the laravel is returning data perfectly. Laravel gives you the collection of the data instead of array. If you need array you can use toArray() method which gives you data in array.
$customers = Customer::with('Xray_machine')->get()->toArray();
dd($customers);

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>

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: Same Variable not working in different view

If i use the variable tests everything works:
My Controller:
public function index()
{
$row = Test::count();
$tests = Test::latest()->paginate($row);
return view('tests.index',compact('tests'));
}
public function show(Test $test)
{
return view('tests.show', compact('test'));
}
My Index-View:
#foreach($tests as $test)
<div class="event">
<h4 class="eventtitle text-j4y-dark">{{ $test->body }}</h4>
Mehr lesen »
</div>
#endforeach
My Show-View:
<h4 class="eventtitle text-j4y-dark">{{ $test->body }}</h4>
but if i use the variable event the index page wokrs so it shows me all of my events but if i click on one event for more details it shows me nothing and nothing works but i don't know why? its the same code only different variables ?
I don't know what to do
My Controller:
public function index()
{
$row = Event::count();
$events = Event::latest()->paginate($row);
return view('tests.index',compact('events'));
}
public function show(Event $event)
{
return view('tests.show', compact('event'));
}
My Index-View:
#foreach ($events as $event)
<div class="event">
<h4 class="eventtitle text-j4y-dark">{{ $event->eventtitel }}</h4>
<div class="date"><i class="far fa-calendar-alt"></i>{{ date("d.m.Y", strtotime($event->datum)) }}</div>
<p class="eventtext" id="eventtext">{{ $event->eventbeschreibung }}</p>
Mehr lesen »
</div>
#endforeach
My Show-View:
<div class="event">
<h4 class="eventtitle">{{ $event->eventtite l}}</h4>
<div class="date"><i class="far fa-calendar-alt"></i>{{ date("d.m.Y", strtotime($event->datum)) }}</div>
<p class="eventtext" id="eventtext">{{ $event->eventbeschreibung }}</p>
</div>
if i use dd($test) it shows me this:
Test {#692 ▼
#fillable: array:1 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:4 [▶]
#original: array:4 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
if i use dd($event) it shows me this:
Event {#660 ▼
#fillable: array:5 [▶]
+timestamps: false
#connection: null
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: false
+wasRecentlyCreated: false
#attributes: []
#original: []
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
if i use echo $event in my controller
it shows me this: []
if i use print_r($event)
it shows me this:
App\Event Object ( [fillable:protected] => Array ( [0] => firmenname [1] => eventtitel [2] => eventbeschreibung [3] => datum [4] => anhang ) [timestamps] => [connection:protected] => [table:protected] => [primaryKey:protected] => id [keyType:protected] => int [incrementing] => 1 [with:protected] => Array ( ) [withCount:protected] => Array ( ) [perPage:protected] => 15 [exists] => [wasRecentlyCreated] => [attributes:protected] => Array ( ) [original:protected] => Array ( ) [changes:protected] => Array ( ) [casts:protected] => Array ( ) [dates:protected] => Array ( ) [dateFormat:protected] => [appends:protected] => Array ( ) [dispatchesEvents:protected] => Array ( ) [observables:protected] => Array ( ) [relations:protected] => Array ( ) [touches:protected] => Array ( ) [hidden:protected] => Array ( ) [visible:protected] => Array ( ) [guarded:protected] => Array ( [0] => * ) )
Well, there are lot of issue with you code. First thing is the pagination.
$row = Event::count(); //This is basically counting all the events you have
$events = Event::latest()->paginate($row); // And here u telling to pageinit with all events in single page.
I personally do not think it is the right way. If I had to do I would do this way
$events = Event::orderBy('created_at','desc')->get(); //This will allthe even in single page with the latest one.
If you only need all the events and sorting is not required I would do like this
$events = Event::all(); //This is give all the events
Coming back to your question.
A variable defined inside a controller method stays inside that method and the view that method is rendering. It does not pass another blade until and unless you are declaring it globally in the provider.
For your case, i would do something like this
Route
Route::get('events',['as'=>'events','uses'=>'ControllerName#index']);
Route::get('event/{id}',['as'=>'event.detail','uses'=>'ControllerName#show']);
Controller
public function index()
{
$data['events'] = Event::orderBy('created_at','desc')->get();
return view('tests.index',$data);
}
public function show($id)
{
$data['eventDetail'] = Event::where('id',$id)->first();
return view('tests.show',$data);
}
Index view
#foreach ($events as $event)
<div class="event">
<h4 class="eventtitle text-j4y-dark">{{ $event->eventtitel }}</h4>
<<CODE HERE MORE CODE >>
Mehr lesen »
</div>
#endforeach
Event detail view
<div class="event">
<h4 class="eventtitle">{{ $eventDetail->eventtite l}}</h4>
<div class="date"><i class="far fa-calendar-alt"></i>{{ date("d.m.Y", strtotime($eventDetail->datum)) }}</div>
<p class="eventtext" id="eventtext">{{ $eventDetail->eventbeschreibung }}</p>
</div>
Hope this helps

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

Resources