Laravel many to many relationship access value from Controller in blade - php

I have two database table
1. patient
--id
--name
2. report
--id
--description
and pivot talbe
patient_report
--id
--report_id
--patient_id
My Patient Model
class Patient extends Model
{
public function reports()
{
return $this->belongsToMany('App\Report' , 'patient_reports');
}
}
My Report Model
class Report extends Model
{
public function patients()
{
return $this->belongsToMany('App\Patient' , 'patient_reports');
}
}
My ReportControlller
public function viewList($reportFloor = null)
{
$report = Report::orderBy('created_at' , 'desc')->paginate(50);
return view('admin.report_list' , ['reports' => $report]);
}
Database : patients table have report_id column and reports table have patient_id column
N.B : I want to find the patient name who has a report. And i am using the laravel dynamic properties like that ---
And finally my blade
#foreach ($reports as $report)
{{ $report->patients->name }}
#endforeach
But it provides an error like that

Try this:
#foreach ($reports->patients as $patient)
{{ $patient->name }}
#endforeach

As the error implies, you're attempting to access the name attribute on a collection. To fix you should change:
#foreach ($reports as $report)
{{ $report->patients->name }}
#endforeach
to:
#foreach ($reports as $report)
#foreach ($report->patients as $patient)
{{ $patient->name }}
#endforeach
#endforeach

In your controller, i would first find the patients and afterwards get their reports.
$patients = Patient::with('reports')->get();
And then in the view i would do:
//This will first get all the patients
#foreach ($patients as $patient)
// This will get each of patients relational reports
#foreach ($patient->reports as $report)
{{ $report->name }}
#endforeach
#endforeach

Related

How can I get field_name from the first table using relationship between two models using laravel 6?

I have two tables with two models and make a reactionship to can get the field_name from the first table :-
First Model:
class KpcField extends Model
{
public function concession(){
return $this->hasMany(Concessions::class);
}
}
Second Model :
class Concessions extends Model
{
public function kpcField(){
return $this->belongsTo(KpcField::class);
}
}
And trying to retreive the field_name in concession view but it showed (Trying to get property field_name of non-object)
Using the foreach to show the data in table :
#foreach ($show_concessions as $show_concession)
<td> {{ $show_concession->kpcField->field_name}} </td>
#endforeach
You can Try This :
#foreach ($show_concessions as $show_concession)
#foreach ($show_concession->kpcField as $item)
<td> {{ $item->field_name}} </td>
#endforeach
#endforeach

Trying to get property '' of non-object (View:

I am trying to fetch a user based on their corresponding District/ area by the ID stored in the user table,
I am able to fetch the result for District where as for the Area, I am getting error,
Trying to get property 'area_name' of non-object (View:
user-index.blade.php)
User
id | district_id | area_id | user_name
District
id | district_name
area
id | district_id | area_name
Controller
$users = Users::simplePaginate(5);
return view('user-index',compact('users'));
Model
User
public function districts(){
return $this->belongsTo('App\Districts','district_id','id');
}
public function areas(){
return $this->belongsTo('App\Area','area_id','id');
}
blade
#foreach ($users as $user)
{{$user-> first_name}} - I get result
{{$user->districts->district_name}} - I get result
{{$user->areas->area_name}} -- I get error
#endforeach
Try this in your controller:
$users = Users::with('areas')->with('districts')->simplePaginate(5);
return view('user-index',compact('users'));
Edit Answer:
In User Model:
public function districts() {
return $this->belongsTo('App\Districts','district_id','id');
}
In District Model:
public function areas() {
return $this->belongsTo('App\Area','district_id','id');
}
And In you Controller, you will fetch the relation like this:
$users = Users::with('districts.areas')->simplePaginate(5);
return view('user-index',compact('users'));
I hope it would be helpful.
Error occurs becouse same user does not have area. For fix it use this
#foreach ($users as $user)
{{$user->first_name}}
{{$user->districts->district_name ?? ''}}
{{$user->areas->area_name ?? ''}}
#endforeach
or
#foreach ($users as $user)
{{$user-> first_name}}
#if($user->districts)
{{$user->districts->district_name}}
#endif
#if($user->areas)
{{$user->areas->area_name}}
#endif
#endforeach
Also for belongs to relations use singulare name
public function district(){
return $this->belongsTo('App\Districts','district_id','id');
}
public function area(){
return $this->belongsTo('App\Area','area_id','id');
}
That case in blade use
#foreach ($users as $user)
{{$user->first_name}}
{{$user->district->district_name ?? ''}}
{{$user->area->area_name ?? ''}}
#endforeach
And for avoid lazy loading in controller use
$users = Users::with(['area', 'district'])->simplePaginate(5);
return view('user-index',compact('users'));
Try in your controller
$users = Users::with(['areas','districts'])->simplePaginate(5);
return view('user-index',compact('users'));
In your blade file check relationship is set or not.
#foreach ($users as $user)
{{ $user->first_name }}
{{ $user->districts ? $user->districts->district_name : '' }}
{{ $user->areas ? $user->areas->area_name : '' }}
#endforeach

Laravel(how to bring two columns from two separate tables in one .blade file) without touching the DB?

What is the most effective way for returning data from two tables in on view?
Like an employee check the vehicle for each order.
Route::get('orderVehicle',"adminController#orderVehicle");
public function orderVehicle(Request $reques){
$orders = new Order;
$vehicles = new Vehicle; $orders->id; $vehicles->id; return view('adminVeiw.orderVehicle',compact('orders','vehicles')); }
#foreach($orders as $or) {{ $or->id }} #endforeach {{ $vehicles->id }}
And the error is
"Trying to get property 'id' of non-object (View:
/var/www/html/full-Restaurant-App-Using-Laravel/resources/views/adminVeiw/orderVehicle.blade.php)"
So any suggestions?
do this if you don't wanna change your code in controller
#foreach($orders as $or)
#if(!empty($or->id))
{{ $or->id }}
#endif
#endforeach
#if(!empty($vahicles->id))
{{ $vehicles->id }}
#endif
in this case you won't get error but i don't know how you wanna this works for you,
i hope it helps
public function orderVehicle()
{
$orders = Order::create();
$vehicles = Vehicle::create();
return view('adminVeiw.orderVehicle', compact('orders', 'vehicles'));
}

Not getting question Model's values in Laravel 5.6

I'm using Laravel 5.6 and I have created two Models Question and User Model and these are linked to each other using one to many relation as:
Question Model
public function user() {
return $this->belongsTo('App\User');
}
User Model
public function questions() {
return $this->hasMany('App\Question');
}
And my controller code is:
public function index()
{
$user = User::all();
return view('home', compact('user'));
}
So, i'm trying to get question title and I have written this code in blade:
#foreach($user as $user)
{{ dd($user->questions->questions_title) }}
#endforeach
But getting error undefined index questions_title, but if only write this {{ dd($user->questions) }} it gave me all questions, so how to fix it.
I have also tried {{ dd($user->questions['questions_title']) }} but not fixed.
You'll want to loop over your questions relationship to see your question:
#foreach($user as $u)
#foreach($u->questions as $question)
{{ dd($question->questions_title) }}
#endforeach
#endforeach
Note: I changed $user to $u
In your controller, you are not eager loading your questions relationships. Change your code to the following:
public function index()
{
$user = User::with('questions')->get();
return view('home', compact('user'));
}
Using the with() method will load all specified relationship with the eloquent query. After this, you will need to loop through the questions collection using the ->each() collection method.
#foreach($users as $user)
#foreach($user->question as $question)
{{ $question->question_title }}
#endforeach
#endforeach
No need for two foreach loops we can simply use one like below:
#foreach ($user->questions as $question)
{{ dd($question->questions_title) }}
#endforeach

Laravel : Explode array with relation belongsTo to model

I want to explode array value and have successfully doing so by using this code :
#foreach(explode('.', $comment->topic_id) as $topic)
{{ $topic }}
#endforeach
This is the output
Topic : 1,2
The problem is, I want to implement relation belongsTo to the topic_id. When I add the relation and run the code, unfortunately only one of the value is shown.
#foreach(explode('.', $comment->getTopic->topic) as $topic)
{{ $topic }}
#endforeach
This is my model
public function getTopic()
{
return $this->belongsTo('App\Topic', 'topic_id', 'id');
}
Output :
Topic : Laravel
What is the right way to call this array? Please help me. Thank you.
You can't use relationship in this case. If you simply looking for solution then you could do something like the following:
<?php $topic_ids = explode('.', $comment->topic_id);
$topics = App\Topic::whereIn(id, $topic_ids)->get();
?>
#foreach($topics as $topic)
{{ $topic }}
#endforeach
BTW you should structure your database more efficiently.
#foreach(explode(',', $item->chapter_id) as $layer)
<?php
$chapters = DB::table('topic_types')->where('id', $layer)->get();
?>
#foreach ($chapters as $ch)
{{$ch->name}} <br>
#endforeach
#endforeach

Categories