Laravel get value from another table based on id - php

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');
}

Related

Attempt to read property "name" on null

Category Model
class Category extends Model
{
use HasFactory;
protected $fillable= ['name','number'];
public function news(){
return $this->hasMany(News::class);
}
News Model
class News extends Model
{
use HasFactory;
protected $fillable= ['cat_id','title','photo','description','author_id','status'];
public function category(){
return $this->belongsTo(Category::class);
}
public function author(){
return $this->belongsTo(Author::class);
}
Author Model
class Author extends Model
{
use HasFactory;
protected $fillable= ['name','status'];
public function news(){
return $this->hasMany(News::class);
}
There is a relationship between the 3 models. And I want to display category name instead of category_id in news-list.blade.php. I am getting a this error.
This is my controller function
public function news_index(){
$news= News::with('category')->get();
return view('News.list',compact('news'));
}
This is my blade page. I got an error when I typed $new->category->name instead of cat_id.
#foreach($news as $new)
<tr>
<th scope="row">{{$loop->iteration}}</th>
<td> {{$new->category->name}}</td>
<td> {{$new->title}}</td>
<td> #if($new->photo)
Görüntüle</td>
#endif
</td>
<td> {{$new->author_id}}</td>
<td> {{$new->description}}</td>
<td> {{$new->status}}</td>
<td>
<a class="btn btn-danger" onclick="return confirm('Silmek istediğinize emin
misiniz?')" href="{{route('news_delete', $new->id)}}"><i class="fa fa-trash"></i></a>
<a class="btn btn-primary" href="{{route('news_update',$new->id)}}"><i class="fa
fa-pen"></i></a>
</td>
</tr>
#endforeach
Here is my news migration table
public function up()
{
Schema::create('news', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('cat_id');
$table->string('title');
$table->string('photo');
$table->longText('description');
$table->unsignedBigInteger('author_id');
$table->boolean('status')->default('1');
$table->foreign('cat_id')->references('id')->on('categories')->onDelete('cascade');
$table->foreign('author_id')->references('id')->on('authors')->onDelete('cascade');
$table->timestamps();
});
}
You need to define your category foreign key explicitly while defining category relationships. Because your category foreign key is not category_id; it's cat_id.
For example, you need to define the category relationship in News model like below:
public function category()
{
return $this->belongsTo(Category::class, 'cat_id');
}
I had the same problem , and i solve it by this :
$new->category->name ?? None'
I guess you need to rewrite you news_index() function.
public function news_index(){
$news = News::with(array('category'=>function($query){
$query->select('id','name');
}))->get();
return view('News.list',compact('news'));
}
i hope this will work. you were not assigning anything to $news variable and passing it to view. $new was null.
<td>{{ $new->category->name ?? 'None' }}</td>
I was having this issue beacuase that name property was associated to a foreign key that could be NULL, so, when you call it throws the error.
You can avoid this specific problem that I have just menctioned like this.
Said by Levis in a comment: For php 8 and above using null safe operator:
$new->category?->name
With this, you can like ignore it if its null and it won't put
anything in that field.
And this one said by abdennour If you want to put some specific value if its null or you're working with PHP below 8:
$new->category->name ?? 'None'
With this, you can avoid if it's null and you're going to put in that field the string None when that value is null.
Check your tables. There has to be a match between the relationships.
Example:
users: id, book_id, name, email
books: id, title, price etc...
In the users table, the book_id, for example 5, must exist in books, otherwise the relationship will be lost and null errors will occur.
Such an ID may not exist. Check the ID column once

Attempt to read property "email" on int - Laravel 8

I have a Work model where one of its attributes is the requestor, I am trying to obtain the requestor´s data (I can already obtain the primary key).
In this way I call the view:
$obras = Obra::all();
return view("obra.index", compact("obras"));
The view:
#forelse ($obras as $i)
<li>{{ $i->requestor_id->email }}</li>
#empty
The relationship in the work model:
public function requestor_id(){
return $this->hasOne(User::class);
}
Tables:
Users(applicants) have: id, name, email, password etc.
Work have: id, user_id, start_date etc.
The problem seems to be that I had the relations wrong, I had to use hasOne in the requester model (in the end I used hasMany because someone can create more than one work) and in the work model use belongsTo.
IMPORTANT note: the name of the function in the model cannot be the same as the name of a field in your table. Also in my case the column names do not follow the laravel/eloquent nomenclature so another parameter is added to belongsTo with the field name.
Work model:
public function solicitante(){
return $this->belongsTo(User::class, "requestor_id");
}
Requestor model:
public function obra(){
return $this->hasMany(Obra::class, "requestor_id");
}
And how to obtain requester data: $obra->solicitante->email
I think it's because of the name of the relation. You can try to renaming it to requestor. Laravel has some internal behavior runing on underscore. It might return only the id.
public function requestor()
{
return $this->hasOne(User::class);
}
import use App\Models\Obra; in the Controller.
use App\Models\Obra;
$obras = Obra::all();
return view("obra.index", compact("obras"));
Returned function must be same table name exm:
public function obra(){
return $this->hasMany(Obra::class, "requestor_id");
}
table name must be obra

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.

Laravel5.8 belongsTo relation not working for foreach loop

I'm working on Laravel relation using hasMany and belongsTo. It work fine for hasMany relation but I have problem on belongsTo for collection foreach loop. This is my categories table.
id name
--------------
1 food
And products table.
id name category_id
----------------------------------
1 pizza 1
2 hamburger 1
Below is hasMany product model.
# Product.php
public function products()
{
return $this->hasMany(Product::class);
}
Below is belongsTo category model.
# Category.php
public function category()
{
return $this->belongsTo(Category::class, 'id');
}
I got an error in blade:
Trying to get property of non-object
<tbody>
#foreach ($products as $product)
<tr>
<td> {{ $product->category->name }} </td>
</tr>
#endforeach
</tbody>
Any advice or guidance on this would be greatly appreciated, Thanks
The problem is the method defintion. The second parameter of the belongsTo method is the foreign key column name. Try this:
# Product.php
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
}
But, given that your foreign key is the model name followed by _id (category_id), Laravel will look up for this key by default.. so you could simplify it like this:
# Product.php
public function category()
{
return $this->belongsTo(Category::class);
}
From the documentation:
... In the example above, Eloquent will try to match the post_id
from the Comment model to an id on the Post model. Eloquent
determines the default foreign key name by examining the name of the
relationship method and suffixing the method name with a _ followed
by the name of the primary key column. However, if the foreign key on
the Comment model is not post_id, you may pass a custom key name
as the second argument to the belongsTo method:
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post', 'foreign_key');
}
Category.php
public function category()
{
return $this->belongsTo(Category::class, 'category_id');
}
Instead of 'id' in category() use 'category_id'..... as you have given category_id as foreign key ....so laravel will search for it...

Laravel cannot retrieve data using one to many not working

I have a problem with one to many relationship in Laravel. I cannot retrieve my data from database. My codes are following.
Doctor.php
public function cities()
{
return $this->belongsTo('App\City');
}
City.php
public function doctor()
{
return $this->hasMany('App\Doctor');
}
view
#foreach($doctors as $doctor)
<tr>
<td data-title="ID">{{ $doctor->id }}</td>
<td data-title="Name">{{ $doctor->name }}</td>
<td data-title="Hospital">{{ $doctor->hospital }}</td>
<td data-title="Designation">{{ $doctor->designation }}</td>
<td data-title="City">{{ $doctor->cities->name }}</td> <!-- problem in this line -->
</tr>
#endforeach
When I try to view the data an error has been shown:
ErrorException in 3d7f581c490d492093e6e73f8ebd29525504e56b.php line 46:
Trying to get property of non-object (View: D:\xampp\htdocs\tourisms\root\resources\views\doctors\index.blade.php)
On the belongsTo side of the relationship, when the foreign key name is not specified, it is built using the name of the relationship. In this case, since your relationship is named cities, Laravel will look for the field doctors.cities_id.
If your foreign key is not cities_id, then you need to either change the name of your relationship method, or specify the name of the foreign key:
public function cities() {
return $this->belongsTo('App\City', 'city_id');
}
// or, better:
public function city() {
return $this->belongsTo('App\City');
}
Also, as mentioned by #Christophvh, the naming of your relationships is a little off, but not programmatically incorrect. It makes more sense and is more readable when belongsTo/hasOne relationships are named singular, and belongsToMany/hasMany relationships are named plural.
You are trying to loop a Collection and not an array.
2 solutions:
1)
add ->get(); when you are calling your relationship in your controller
2)
use
#foreach($doctors->all() as $doctor)
instead of
#foreach($doctors as $doctor)
Also a quick tip:
Your naming is not really telling what you are doing. You should swap them around like below. 'A doctor belongs to a city' & 'A city has many doctors'
Doctor.php
public function city()
{
return $this->belongsTo('App\City');
}
City.php
public function doctors()
{
return $this->hasMany('App\Doctor');
}

Categories