Laravel : Eloquent Relationships not work. Cannot show relationships in view - php

I cannot show relationships in view after I set Eloquent Relationships in Model already.
In Model: Art_obj
class Art_obj extends Model
{
protected $table = 'art_objs';
protected $fillable = ['Id_no','Artist','Year','Title','Description','Origin','Epoch','Picture','Type_of_art'];
public function Painting(){
return $this->hasOne(Painting::class,'Id_no');
}
}
In Model: Painting
class Painting extends Model
{
protected $table = 'paintings';
protected $fillable = ['art_obj_Id_no','Paint_type','Drawn_on','Style'];
public function Art_obj(){
return $this->belongsTo(Art_obj::class,'Id_no');
}
}
In PaintingController
public function index()
{
$paintings = Painting::with('Art_obj');
return view('ArtObj.Painting', compact('paintings'));
}
in Painting.blade.php
<table class="table table-bordered table-striped">
<tr>
<th>Title</th>
<th>Paint type</th>
<th>Drawn on</th>
<th>Style</th>
</tr>
#foreach($paintings as $row)
<tr>
<td>{{$row->Art_obj->Title}}</td>
<td>{{$row['Paint_type']}}</td>
<td>{{$row['Drawn_on']}}</td>
<td>{{$row['Style']}}</td>
</tr>
#endforeach
</table>
It does not have any field show in view.
enter image description here

If you aren't using id as your model's primary key, you need to set the primary key property in your models:
protected $primaryKey = 'Id_no';
Eloquent will also assume that each table has a primary key column named id. You may define a protected $primaryKey property to override this convention.
In addition, Eloquent assumes that the primary key is an incrementing integer value, which means that by default the primary key will be cast to an int automatically. If you wish to use a non-incrementing or a non-numeric primary key you must set the public $incrementing property on your model to false. If your primary key is not an integer, you should set the protected $keyType property on your model to string.
In addition, the relation must set the correct foreign and owner keys:
public function Art_obj(){
return $this->belongsTo(Art_obj::class,'Id_no', 'art_obj_Id_no');
}
and then retrieve the data:
$paintings = Painting::with('Art_obj')->get();
You should also check if the relation exists before attempting to access it:
#foreach($paintings as $row)
<tr>
#if (!is_null($row->Art_obj))
<td>{{$row->Art_obj->Title}}</td>
#else
<td>No Title</td>
#endif
<td>{{$row->Paint_type}}</td>
<td>{{$row->Drawn_on}}</td>
<td>{{$row->Style}}</td>
</tr>
#endforeach

You have not fetched data yet. Change your query to:
$paintings = Painting::with('Art_obj')->get();

Related

Retrieving data based on One To Many Relationship

I have two tabled called categories and resources table.
Basically each resource has a category and the category id is saved on a column called resource_category_id in resources table.
So in order to setup One To Many relationship between the Models, I did these:
Category:
class Category extends Model
{
protected $table = "categories";
protected $guarded = [];
public function resources()
{
return $this->hasMany(Resource::class);
}
}
Resource:
class Resource extends Model
{
protected $table = "resources";
protected $guarded = [];
public function category()
{
return $this->belongsTo(Category::class, 'resource_category_id');
}
}
And now I want to show all categories and the resources and that have the same resource_category_id like this:
#php($menuCounter = 0)
#foreach($categories as $cat)
<tr>
<td style="text-align:center">{{ ++$menuCounter }}</td>
<td style="text-align:center">{{ $cat->category_name }}</td>
<td>
<ul>
#foreach($category->resources() as $resource)
<li>{{ $ress->resource_name }}</li>
#endforeach
</ul>
</td>
</tr>
#endforeach
But now the categories are all appearing but the resources does not be shown and also no error returns!
So what's going wrong here?
How can I show the resources according to resource_category_id via Eloquent relationships methods?
Instead of:
#foreach($category->resources() as $resource)
do
#foreach($category->resources as $resource)
The first one is loading the builder, the second one the collection.
You can also specify the foreign key for resources relationship in Category Model:
public function resources()
{
return $this->hasMany(Resource::class, 'resource_category_id');
}

Laravel get value from another table based on id

I want to get department_name from department table
with
table department = id, department_name, total_employee
table employee = id, employee_name, id_department, email, telephone, gender, status
I tried
model.Employee
public function department()
{
return $this->belongsTo(Department::class);
}
controllers.EmployeeControllers
public function index()
{
$data_employee = Employee::with('department')->get();
return view ('employee.index', compact('data_employee '));
}
with view
#forelse ($data_employee as $item)
<tr>
<td class="text-center">{{ $item->employee_name}}</td>
<td class="text-center">{{ $item->department->department_name}}</td>
<td class="text-center">{{ $item->email}}</td>
<td class="text-center">{{ $item->telephone}}</td>
</tr>
#endforelse
But then it said
Attempt to read property "department_name" on null
What do I do wrong.
First of all you need to write your relationship properly.
public function department()
{
// You have to provide correct model name here.
return $this->belongsTo(Department::class);
}
Secondly Eloquent determines the foreign key name by examining the name of the relationship method and suffixing the method name with _id. So, in your case, Eloquent assumes that the Employee model has a department_id column. But, the foreign key on the Phone model is not department_id , you may pass a custom key name as the second argument to the belongsTo method
public function department()
{
return $this->belongsTo(Department::class, 'id_department');
}
Source here
Please replace model.Employee
public function department()
{
return $this->belongsTo(Department::class, 'id_department');
}

Laravel 7 : trying to get the name instead of id

I'm trying to get the client name , address ect.. based on their relationship, but when I am trying to get the name for exaple i get the error Trying to get property of 'name' of a non-object.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Client;
class Evaluation extends Model
{
protected $table = 'evaluations';
protected $fillable = [
'expert',
];
public function client() {
return $this->belongsTo(Client::class);
}
}
Controller
public function index()
{
$evaluations = Evaluation::with('client')->get();
$users= auth()->user();
return view('evaluation.index', ['evaluations' => $evaluations]);
}
view
#if (count($evaluations) < 1)
<h1>Nici o evaluare nu a fost gasita.</h1>
#else
#foreach ($evaluations as $evaluation)
<tr>
<td class="pl-1">{{$evaluation->id}}</td>
<td class="pl-1">{{$evaluation->expert}}</td>
<td class="pl-1">{{$evaluation->gram1}}</td>
<td class="pl-1">{{$evaluation->client_id}}</td>
#php
dd($evaluation->client_id->nume)
#endphp
<td> Printeaza</td>
</tr>
#endforeach
#endif
An I also have to mention that in my table is nume instead of name it's no english project.
SOLVED, Relationship and all there was good, all I Needed to do was to create an input hidded for taking the id and add the Id on protected $fillable on client model not on evaluation model. It's work and in the view you have to call it like {{$evaluation->client->nume}}, "->client->" = is the relationship that you called. And I SOLVED even the Foreign key problem, in my create_evaluations_table the client_id column was bigInteger and in my create_clients_table the id of client that I wanted to associate was integer. All you need to do if you will have this error is to make them identically like if the id in the table that you want to associate is integer you need to save the integer there also.

Laravel Relationship Composite Primary Key

How to define relationship in Laravel using composite keys?
I have 2 tables which have 2 primary keys, order [id_order, id_trip] and detail order [id_trip, id_seat].
I tried to get $order->detail_order->id_seat in index.blade.php, but the error is Array to string conversion (View: D:\xampp\htdocs\travel\resources\views\order\index.blade.php)
I think I have a mistake in defining relationship in model. Here's my code :
Order.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\CompositeKeyTrait;
class Order extends Model{
use CompositeKeyTrait;
protected $table = "order";
protected $fillable = [
'id_order',
'id_trip',
'id_users_customer',
'date_order',
'id_users_operator'
];
protected $primaryKey = ['id_order', 'id_trip'];
public function detail_order(){
return $this->hasMany(Detail_Order::class);
}
}
Detail_Order.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\CompositeKeyTrait;
class Detail_Order extends Model{
use CompositeKeyTrait;
protected $table = "detail_order";
protected $fillable = [
'id_trip',
'id_seat',
'id_users_feeder',
'id_order',
etc
];
protected $primaryKey = ['id_trip', 'id_seat'];
public function order(){
return $this->belongsTo(Order::class, 'id_order', 'id_trip');
}
}
index.blade.php
#foreach($order as $o)
<tr>
<td>{{ $o->detail_order->id_seat }}</td>
</tr>
#endforeach
Does anyone have any idea? Thanks.
Laravel does not support Composite Primary Key. You hit "Array to string conversion" error becouse Laravel try to cast array to string.
protected $primaryKey = ['id_order', 'id_trip'];
You can't. Eloquent doesn't support composite primary keys.
But you can do using an open-source package called LaravelTreats.
Hope this helps you
Ref: https://stackoverflow.com/a/36995763/10765839

Relationship with Pivot Table Laravel's Eloquent and Inner Loops

Ok, can anyone help me with this scenerio? I want to make a loop of Divisions and an inner loop of all the teams in that division using relationships in Eloquent. Been googling and expermenting but can't get the right results.
My tables are as such:
Divisions
division_id INT PK
division_name VARCHAR
...
Teams
team_id INT PK
team_name VARCHAR
...
division_team (pivot table)
id INT PK
division_id INT FK
team_id INT FK
My Models are as such:
DivisionTeamPivot
class DivisionTeamPivot extends \Eloquent {
protected $fillable = [];
protected $table = 'division_team';
public function team(){
return $this->belongsTo('Team');
}
public function division(){
return $this->belongsTo('Division');
}
Divisons
class Division extends \Eloquent {
protected $primaryKey = 'division_id';
public function teams(){
return $this->hasMany('Team','division_team','division_id','team_id');
}
}
Teams
class Team extends \Eloquent {
protected $primaryKey = 'team_id';
public function division(){
return $this->belongsTo('Division','division_team','team_id','division_id');
}
}
My Controller has:
$divisions = DivisionTeamPivot::with('Team','Division')->get();
My View:
<section class="panel">
<header class="panel-heading">
<h5>{{$division->division->division_name}} Division {{$i}}</h5>
</header>
<table class="table">
<thead>
<tr>
<th></th>
<th>Team Name</th>
<th class="center">Total Points</th>
<th class="center">Rank</th>
</tr>
</thead>
<tbody>
#foreach($division->team as $team)
<tr>
<td width="75"><img src="/img/logos/{{team->team_logo}}" width="50"></td>
<td> {{team->team_name}}</td>
<td class="center">1,345</td>
<td class="center">1</td>
</tr>
#foreach
</tbody>
</table>
</section>
What I want to do is loop over the divisions and then sub loop the teams that are in those divisions. I saw someone on here to make a pivot table model but when I use it, it loops over all the same divisions based off the division_id table in the pivot but I get the name. Its creating one team per duplicate division. I need them grouped based on the divisions they are in. And, actually, I still can't get the teams name to show. I also really want the eager loading to be working so I get the most efficient queries I can. Thanks!!
For making the many-to-many relationship you need to use belongsToMany instead of belongsTo in your both models (Division and Team) and you don't need to use another model as DivisionTeamPivot for pivot table. So in Division and Team use belongsToMany method:
// Division Model
public function teams(){
return $this->belongsToMany('Team', 'division_team', 'division_id', 'team_id');
}
// Team Model
public function divisions(){
return $this->belongsToMany('Division', 'division_team', 'team_id', 'division_id');
}
Make the query like this:
$divisions = Division::with('teams')->get();
return View::make('viewname')->with('dvisions', $divisions);
In the view the nested loops could be something like this:
#foreach($divisions as $division)
{{ $division->division_name }}
#foreach($division->teams as $team)
{{ ... }}
{{ $team->team_name }}
#endforeach
#endforeach

Categories