relationship and blade in laravel - php

I have 3 table as mentioned below.
Table 1(user):
id username password Name Age
Table 2(tasks):
id task_name description
Table 3(logs)
id user_id task_id date hours
Table Relationships:
user has_many logs
task has_many logs
logs belongs_to user
logs belongs_to task
what i am trying to achieve is to get the logs with the user Name, task Name, date and hours.
Controller:
return View::make('log.index')
->with('logs',log::all());
Blade template
#foreach($logs as $log)
<tr>
<td>{{$log->id}}</td>
<td>{{$log->users()->name}}</td>
<td>{{$log->tasks()->name}}</td>
<tr>
#endforeach
but unable to fetch users Name and Tasks name from the respective table. any help is appreciated.

A better way is to define inverse hasMany relation in your Model, as documented here
So in your logs model, probably you need to define:
class Log extends Eloquent {
protected $table = "logs";
public function user(){
return $this->belongsTo('User');
}
public function task(){
return $this->belongsTo('Task');
}
}
Then in your view you can either use :
$log->user()->first()->name
or even better, by using Dynamic Properties:
$log->user->name

$log->users() and $log->tasks() returns a query object. Below, each call returns the result which is the same as calling $log->users()->get() and $log->tasks()->get(). Because the relationships are many to many, you'll need to iterate over $log->users and $log->tasks to retrieve each record.
#foreach($logs as $log)
<tr>
<td>{{$log->id}}</td>
<td>
#foreach($log->users as $user)
{{$user->name}},
#endforeach
</td>
<td>
#foreach($log->tasks as $task)
{{$task->name}},
#endforeach
</td>
<tr>
#endforeach
If you want a specific user/task attached to a log you'll have to build a query.
#foreach($logs as $log)
<tr>
<td>{{$log->id}}</td>
<td>{{$log->users()->where('id', '=', $userID)->first()->name}} </td>
<td>{{$log->tasks()->where('id', '=', $taskID)->first()->name}} </td>
<tr>
#endforeach

Related

Many to many relations LARAVEL

I have a problem retrieving data from a third table, as you can see I have three tables:
Models : id , code , title
levels : id , code . title
models_level : model_id,level_id
I have as function :
$model = model::paginate(10);
$level = level::all();
$models_level = models_level::all();
return view('pg',compact('model','level','models_level'));
How can I retrieve the level name based on the model id retrieved?
Here is my blade
<tbody>
#foreach($model as $f)
<tr class="item{{$f->id}}">
<td style="font-size: 13px;"> {{$f->title}}</td>
<td style="font-size: 13px;">{{$f->code}}</td>
<td style="font-size: 13px;">{{$f->models_level->level_id}}</td>
</tr>
#endforeach
{{ $filiere->links() }}
</tbody>
I need to show the title in level instead of the ID.
in this case I have 2 different tables and the 3 rd is associative
table that contains the two , so I have to pass by model to get
model_level . get the level id depending on the model_id and the go to
level and find the title ..
Models
– id
levels
– id
models_level
– product_id
– shop_id
here models_level table is called as pivot table
app/Model.php
class Model extends Model
{
public function levels()
{
return $this->belongsToMany('App\level','models_level');
}
}
app/level.php
class Level extends Model
{
public function Models()
{
return $this->belongsToMany('App\Shop','models_level');
}
}
$model = model::with('levels')->paginate(10);
return view('pg',compact('model'));
<tbody>
#foreach($model as $f)
<tr class="item{{$f->id}}">
<td style="font-size: 13px;"> {{$f->title}}</td>
<td style="font-size: 13px;">{{$f->code}}</td>
<td style="font-size: 13px;">{{$f->levels[0]->id}}</td>
</tr>
#endforeach
{{ $filiere->links() }}
</tbody>
You can read more about many to many relationships in the docs.
I assume you are using a One to Many relationship and you have the correct methods in you model classes.
This way you can change your controller method to:
$model = model::with('level')->paginate(10);
return view('pq', $model);
and in your blade files loop:
<td style="font-size: 13px;">{{$f->level->title}}</td>
You should read up on eloquent relationships in the laravel documentation:
https://laravel.com/docs/6.x/eloquent-relationships

How to get the username through an id in Laravel?

I am trying to create an offers forum, where some user can create their offers in order to provide their services and I want to show the name of the person that created that offer instead of the id.
In my database I have the two tables:
Offers table:
User table:
In offers I have a column of the professor_id, that is related to the id of users table.
This is what i have in my controller to show the offers:
public function ofertes(){
$ofertes = Oferta::all()->sortByDesc('id');
return view('create.ofertes')->with(compact('ofertes'));
}
and in the blade.php I have that code:
#foreach($ofertes as $oferta)
<tr>
<td>Nom : {{$oferta->professor_id}}</td> <br>
<td>Títol : {{$oferta->titol}}</td> <br>
<td>Descripció: {{$oferta->descripcio}}</td> <br>
<td>Data: {{$oferta->created_at}}</td> <br><br>
</tr>
#endforeach
and that is what is shown:
Where it says nom, how I can show the name instead of the id?
Thank you!
If you have specified the relationship to professor in your Oferta model you can use the following code:
public function ofertes(){
$ofertes = Oferta::with('professor')->latest()->get();
return view('create.ofertes')->with(compact('ofertes'));
}
Your blade:
#foreach($ofertes as $oferta)
<tr>
<td>Nom : {{$oferta->professor->nom}}</td> <br>
<td>Títol : {{$oferta->titol}}</td> <br>
<td>Descripció: {{$oferta->descripcio}}</td> <br>
<td>Data: {{$oferta->created_at}}</td> <br><br>
</tr>
#endforeach
If you haven't specified the relation you should add the following method to your Oferta model (you might need to tweak this a little bit based on your namespaces):
public function professor()
{
return $this->belongsTo(User::class);
}
Very easy
public function ofertes(){
$ofertes = Oferta::with('professor')->latest()->get();
$users = User::all();
return view('create.ofertes')->with(compact('ofertes', 'users'));
}
In blade file:
<td>Nom : #foreach ($users as $user)
#if ($oferta->professor_id === $user->id) $user->nom $user->cognom
#endif
#endforeach
</td><br>
Join two table like
$oferta = DB::table('users')
->join('offers','users.id','=','offers.professor_id')
->select('offers.*','users.nom')
->orderby('offers.id','DESC')->get();
Then in place of {{$oferta->professor_id}}, replace {{$oferta->nom}}
Your problem should be solved

How to show two table data in a view using Eloquent Relationship in Laravel

I have two Table names are User and Role Table. I have set manyTomany relations between them using pivot table name Role_User in Laravel Eloquent.
Now, I want to show both table data in together a view using Eloquent Relationship.(e.g. I want to show in my view a user from users table contain which role in roles table )
Here, is my eloquent relations.
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function users()
{
return $this->belongsToMany('App\User');
}
My, Eloquent Relationship Query.
$users=User::with('roles')->get();
return view('admin',compact('users'));
I'm try in my View.
#foreach($users as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{$user->email}}</td>
<td>{{$user->roles->name}}</td>
<td></td>
</tr>
#endforeach
When you call $user->roles, you get a collection of the roles back. So if you want to display them all in a single string, all you have to do is implode the collection on that string:
<td>{{$user->roles->implode('name', ', ')}}</td>
Your $user->rules is instance of Collection of Role model. You can use one more foreach:
#foreach($users as $user)
//do something with user
#foreach($user->roles as $role)
{{$role->name}}
#endforeach
#endforeach
This will work in Laravel 5.0 and above
If we have two Model User and Mark. Then Inside the User Model make a function for relation with Mark. Example
public function marks()
{
return $this->hasMany('App\Models\Mark');
}
So, If you want to display the User name will all his marks. Then inside the controller perform following way.
public function getUserMarks(){
$result = User::select('email', 'name')->where('email', 'usermail#example.com')->with(['marks'])->get();
return view('welcome', compact('results'));
}

Trying to get property of non-object - Laravel 5

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.

Laravel Eloquent : belongsTo relationship - Error: Trying to get property of non-object

First time to try laravel eloquent relatioinstip
I know it's really simple but I am getting this error don't know what's wrong with it
I have 2 tables in data base, news and news_image
in database
Tables:
news
id | header | details
news_image
id | image | news_id
And have 2 models News , newsImage
newsImage model :
class newsImage extends Eloquant {
protected $table = 'news_image';
public function news()
{
return $this->belongsTo('News');
}
}
News model
class News extends Eloquent
{
protected $table = 'news';
public $timestamps = false;
public function image()
{
return $this->hasMany('newsImage');
}
}
The view:
foreach($news as $new)
<tr>
<td> {{$new->id}} </td>
<td> {{ $new->header}}</td>
<td> {{ $new->details }}</td>
</td> {{$new->news->image}}</td>
</tr>
when I run this it's get error :
Trying to get property of non-object (View: /var/www/html/clinics/app/views/news/index.blade.php)
Any ideas on what could be causing this error?
First, assuming what you are passing to your view is an array or Collection of News objects, you should probably be using $new->image to access the News Item relation. By defining the function image() in your News model, you can access the relation with either the ->image or ->image() calls. In either case, what you need to call is probably
$new->image->first()->image
To break that down:
->image gets the Collection of NewsImage relations
->first() gets the first item in the Collection
->image (the secone one) gets the image field from that NewsImage
If the Collection has more than one item, you can instead loop over it to get all of the images as shown in the other answer.
There are a couple things I would change:
In your News model, change the relationship from "image" to "images" since it's a one to many relationship. It just keeps your code clean.
Your foreach loop in your view should loop through all the news models, but remember that each news model has multiple images, so you should have another loop inside your existing loop to display the images, i.e. foreach ($new->images as $image)
#foreach ($news as $new)
<tr>
<td> {{$new->id}} </td>
<td> {{ $new->header}}</td>
<td> {{ $new->details }}</td>
<td>
#foreach ($new->images as $image)
{{ $image->image }}
#endforeach
</td>
</tr>
#endforeach

Categories