I have 2 relationships that point to the same User model: operador() and profesional().
class Cita extends Model
{
public function paciente(){
return $this->belongsTo('\App\Models\Paciente');
}
public function profesional(){
return $this->belongsTo('\App\Models\User');
}
public function operador(){
return $this->belongsTo('\App\Models\User');
}
}
In the view I call them like this:
#foreach ($comisiones as $comision)
<tr>
<td>{{ $comision->paciente->name }}</td>
<td>{{ $comision->profesional->name }}</td>
<td>{{ $comision->operador->name }}</td>
<td>{{ number_format($comision->total, 0, '.', '.') }}</td>
<td>{{ $comision->estado }}</td>
</tr>
#endforeach
The program crashes on me when it tries to call $commision->operador->name. If I leave it as a comment it works without problems. But it gives me an error when I have the 2 relations at the same time.
Can I have 2 relationships pointing to the same model? And if not, what alternative do I have? Thanks
For the fact that you are using belongTo relationship, that means User is the parent model and Professional and Operador are the child model.
Hence, it is expected that the table for Professional has a column called user_id, thesame thing for the Operador table, it should have user_id column.
With this the relationship will work just fine.
Yes, you can have 2 relationships pointing to the same model.
When you write :
public function operador(){
return $this->belongsTo('\App\Models\User');
}
Laravel expects that The Migration (The table citas) has a column named operador_id. So Yes you can have multiple relationships to the same model.
Related
I'm the beginner of laravel 5.4. I just want to ask. I want to display in Assignments table the Collectors but it doesn't show.
Screenshot of the Assignments Index
Code in my Assignment index.blade.php
<td>{{ $assignment->collector['firstname'] }} {{ $assignment->collector['lastname'] }}</td>
Assignment.php model
public function collectors()
{
return $this->belongsToMany(Collector::class);
}
Collector.php model
public function assignments()
{
return $this->belongsToMany(Assignment::class);
}
AssignmentsController
public function index()
{
$assignments = Assignment::all();
return view('assignments.index', compact('assignments'));
}
I search to how to display the collectors with both many to many relationship. I read the doc about using pivot but I had still errors about that. Can you help me resolving this? Thanks
$collector is an object, not an array. Use -> syntax to access properties on individual collector models:
$collector->firstname
Since the relationship is many to many you need two loops:
#foreach($assignments as $assignment)
#foreach($assignment->collectors as $collector)
<td>{{ $collector->firstname }} {{ $collector->lastname }}</td>
#endforeach
#endforeach
If you find you often need two fields together, like first and last names, you can create an accessor on the Collector model to easily join them:
public function getFullNameAttribute()
{
return $this->getAttribute('firstname') . ' ' . $this->getAttribute('lastname');
}
Allowing you to then do:
#foreach($assignments as $assignment)
#foreach($assignment->collectors as $collector)
<td>{{ $collector->fullname }}</td>
#endforeach
#endforeach
There are numerous questions concerning my problem but it's never been the case I encounter, so here my code:
<td>{{ $note->title}}</td>
<td>{{ App\User::where('id', $note->user)->first()->name }}</td>
<td>{{ date("d.m.Y H:i:s", strtotime($note->created_at)) }}</td>
<td>{{ date("d.m.Y H:i:s", strtotime($note->updated_at)) }}</td>
Everything works fine so far, except for
<td>{{ App\User::where('id', $note->user)->first()->name }}</td>
I figured out that the problem is $note->user and it throws
(2/2) ErrorException
Trying to get property of non-object
which doesn't make ANY sense to me since $note->title above and $note->created_at work like a charm. Any ideas?
You should always check if a user exists:
$user = App\User::where('id', $note->user)->first();
Then in the view:
{{ is_null($user) ? 'No user with specified ID' : $user->name }}
Also, it's a terrible idea to use Eloquent in a view.
You need to check the existence of user before asking for its name.
Also you can leverage Eloquent relationships which will remove the user retrieval from your view.
Add a user relationship to the Note model
public function user()
{
return $this->belongsTo(\App\User::class, 'user');
}
Then in your view you can call $note->user which will return a App\User instance if found or else null.
So to print user's name
<td>{{ $note->user ? $note->user->name : '' }}</td>
I'm trying to echo out the name of the user in my article and I'm getting the
ErrorException: Trying to get property of non-object
My code:
Models
1. News
class News extends Model
{
public function postedBy()
{
return $this->belongsTo('App\User');
}
protected $table = 'news';
protected $fillable = ['newsContent', 'newsTitle', 'postedBy'];
}
2. User
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
protected $table = 'users';
protected $fillable = ['name', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
}
Schema
table users
table news
Controller
public function showArticle($slug)
{
$article = News::where('slug', $slug)->firstOrFail();
return view('article', compact('article'));
}
Blade
{{ $article->postedBy->name }}
When I try to remove the name in the blade {{ $article->postedBy }} it outputs the id, but when I try to add the ->name there it says Trying to get property of non-object but I have a field namein my table and aUser` model. Am I missing something?
Is your query returning array or object? If you dump it out, you might find that it's an array and all you need is an array access ([]) instead of an object access (->).
I got it working by using Jimmy Zoto's answer and adding a second parameter to my belongsTo. Here it is:
First, as suggested by Jimmy Zoto, my code in blade
from
$article->poster->name
to
$article->poster['name']
Next is to add a second parameter in my belongsTo,
from
return $this->belongsTo('App\User');
to
return $this->belongsTo('App\User', 'user_id');
in which user_id is my foreign key in the news table.
If you working with or loops (for, foreach, etc.) or relationships (one to many, many to many, etc.), this may mean that one of the queries is returning a null variable or a null relationship member.
For example: In a table, you may want to list users with their roles.
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->role->name }}</td>
</tr>
#endforeach
</table>
In the above case, you may receive this error if there is even one User who does not have a Role. You should replace {{ $user->role->name }} with {{ !empty($user->role) ? $user->role->name:'' }}, like this:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ !empty($user->role) ? $user->role->name:'' }}</td>
</tr>
#endforeach
</table>
Edit:
You can use Laravel's the optional method to avoid errors (more information). For example:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ optional($user->role)->name }}</td>
</tr>
#endforeach
</table>
If you are using PHP 8, you can use the null safe operator:
<table>
<tr>
<th>Name</th>
<th>Role</th>
</tr>
#foreach ($users as $user)
<tr>
<td>{{ $user?->name }}</td>
<td>{{ $user?->role?->name }}</td>
</tr>
#endforeach
</table>
I implemented a hasOne relation in my parent class, defined both the foreign and local key, it returned an object but the columns of the child must be accessed as an array.
i.e. $parent->child['column']
Kind of confusing.
REASON WHY THIS HAPPENS (EXPLANATION)
suppose we have 2 tables users and subscription.
1 user has 1 subscription
IN USER MODEL, we have
public function subscription()
{
return $this->hasOne('App\Subscription','user_id');
}
we can access subscription details as follows
$users = User:all();
foreach($users as $user){
echo $user->subscription;
}
if any of the user does not have a subscription, which can be a case.
we cannot use arrow function further after subscription like below
$user->subscription->abc [this will not work]
$user->subscription['abc'] [this will work]
but if the user has a subscription
$user->subscription->abc [this will work]
NOTE: try putting a if condition like this
if($user->subscription){
return $user->subscription->abc;
}
It happen that after some time we need to run
'php artisan passport:install --force
again to generate a key this solved my problem ,
I had also this problem. Add code like below in the related controller (e.g. UserController)
$users = User::all();
return view('mytemplate.home.homeContent')->with('users',$users);
Laravel optional() Helper is comes to solve this problem.
Try this helper so that if any key have not value then it not return error
foreach ($sample_arr as $key => $value) {
$sample_data[] = array(
'client_phone' =>optional($users)->phone
);
}
print_r($sample_data);
Worked for me:
{{ !empty($user->role) ? $user->role->name:'' }}
In my case the problem was in wrong column's naming:
In model Product I've tried to access category relationship instance to get it's name, but both column name and relationship had the same name:
category
instead of:
category_id - for column name
category - for relationship
Setting up key name in relationship definition like
public function category():hasOne
{
return $this->hasOne(Category::class,'category');
}
didn't help because as soon as Laravel found property named category gave up on looking for relationship etc.
Solution was to either:
change property name (in model and database) or
change relationship name (Eg. productCategory )
It wasn't an error in my case. However, this happened to me when I was trying to open users.index, because while testing I've deleted some data from the 'STUDENTS' table and in the 'USERS' table, a foreign key ('student_id') represents the 'STUDENTS' table. So, now when the system tries to access the 'USERS' table in which foreign key ('student_id') is null since the value got deleted from the 'STUDENTS' table.
After checking for hours when I realise this, I insert the same data again in the 'STUDENTS' table and this resolved the issue.
Here is my situation;
I have an agreements table which will list the different types of agreements there are. It's a lookup table basically.
I have a client_agreements table which list which clients have signed up to which type of agreement. I have an agreement_id within this table (foreign key id).
As I am using Laravel, here is my Controller method to view all agreements for a specific client;
public function index($client_id)
{
$client_agreements = Agreement::find($client_id);
return View::make('client_agreements.index')
->with('client_agreements', $client_agreements);
}
Here is my Agreement Model;
class Agreement extends Eloquent {
protected $table = 'agreements';
public function client_agreements(){
return $this->hasMany('ClientAgreement', 'agreement_id');
}
}
So I want to output in the view from the agreements table;
agreement_type
level
and from the client_agreements table;
start_date
expire_date
My View code (which I'm sure is wrong but don't know why) is essentially;
#foreach($client_agreements as $client_agreement)
<tr>
<td>{{ $client_agreement->agreement_type }}</td>
<td>{{ $client_agreement->level }}</td>
<td>{{ $client_agreement->start_date }}</td>
<td>{{ $client_agreement->expire_date }}</td>
</tr>
#endforeach
What am I doing wrong?
You can do it like this:
$client = Client::with('agreements')->find($client_id);
$client_agreements = $client->agreements;
return View::make('client_agreements.index')
->with('client_agreements', $client_agreements);
And in your view:
#foreach($client_agreements as $client_agreement)
<tr>
<td>{{ $client_agreement->agreement_type }}</td>
<td>{{ $client_agreement->level }}</td>
<td>{{ $client_agreement->pivot->start_date }}</td>
<td>{{ $client_agreement->pivot->expire_date }}</td>
</tr>
#endforeach
This would require the following setup:
Client model
class Client extends Eloquent {
public function agreements(){
return $this->belongsToMany('Agreement', 'client_agreements')->withPivot('id', 'start_date', 'expire_date');
}
}
Agreement model
class Agreement extends Eloquent {
public function clients(){
return $this->belongsToMany('Client', 'client_agreements')->withPivot('id', 'start_date', 'expire_date');
}
}
For more information read the Eloquent docs (especially the section about relationships)
Good evening peeps, I'm playing a little bit with Laravel, and I have this situation. I have 2 models and 3 tables to display vital signs from a pacient.
Table pacient:
id
names
birthdate
Table vital_sign:
id
description
unit
table pacient_vital_sign
id
pacient_id
vital_sign_id
first_value
second_value
date_time_taken
And the 2 models:
class Pacient extends Eloquent{
public static $timestamps = false;
public function vital_signs(){
return $this->has_many_and_belongs_to('VitalSign', 'pacient_vital_sign', 'pacient_id', 'vital_sign_id');
}
}
class VitalSign extends Eloquent{
public static $timestamps = false;
public static $table = 'vital_signs';
public function pacients(){
return $this->has_many_and_belongs_to('Pacient', 'pacient_vital_sign', 'vital_sign_id', 'pacient_id');
}
}
And for my view I'm sending the pacient whose vital signs I want to display:
$pacient = Pacient::where('active', '=', 1)->first();
So, based on the documentation I could do this to show the pivotal table data:
#foreach($pacient->vital_signs as $sv)
<tr>
<td>{{ $sv->pivot->date_time_taken }}</td>
<td>{{ $sv->description }}</td>
<td>{{ $sv->pivot->first_value }} {{ $sv->pivot->second_value }}</td>
</tr>
#endforeach
But this way, neither the date_time_taken value nor first_value or second_value is showed. Description is displayed.
Now, if I do something like this
#foreach($pacient->vital_signs()->pivot()->get() as $sv)
<tr>
<td>{{ $sv->date_time_taken }}</td>
<td>{{ $sv->description }}</td>
<td>{{ $sv->first_value }} {{ $sv->second_value }}</td>
</tr>
#endforeach
date_time_taken, first_value and secon_value are displayed but I dont know how to reverse the relationship in order to display the value for the related table column, in this case, description from vital_sign table
So I both cases, I'm missing something. Any ideas? What I'm missings?
Thanks
On the Docs:
By default only certain fields from the pivot table will be returned
(the two id fields, and the timestamps). If your pivot table contains
additional columns, you can fetch them too by using the with() method
So in my case, on both models:
return $this->has_many_and_belongs_to('VitalSign', 'pacient_vital_sign', 'pacient_id', 'vital_sign_id')->with('col1', 'col2', 'coln');
and this will work:
#foreach($pacient->vital_signs as $sv)
<tr>
<td>{{ $sv->pivot->date_time_taken }}</td>
<td>{{ $sv->description }}</td>
<td>{{ $sv->pivot->first_value }} {{ $sv->pivot->second_value }}</td>
</tr>
#endforeach
I found this to be useful, but a quick addendum for Laravel 4:
return $this->belongsToMany('Model','pivot_table','this_id','foreign_id')->withPivot('col1','col2');