Attempt to read property "name" on null - php

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

Related

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.

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...

Primary Key and Foreign Key on Laravel

I know this questions already are asked but I am stuck...
I have 2 tables (clubs and membres):
In my table clubs I have 3 fields id_club, name_club, type_sport_club
Everything is working on my table Clubs
However I am stuck in my table Membres, I don't understand...
My problem is I only get number of my fk and no the name of club...
For information I have 3 fields id_membre, name_membre, fk_club
So...In my database I have this
public function up()
{
Schema::create('membres', function (Blueprint $table) {
$table->increments('id_membre');
$table->string('name_membre');
$table->integer('fk_club')->unsigned();
$table->foreign('fk_club')->references('id_client')->on('clients');
$table->timestamps();
});
}
Then on Model I have this
class Membre extends Model
{
//
protected $fillable = ['name_membre', 'fk_club'];
}
After for Controller I have this
public function index()
{
$membres = Membre::oldest()->paginate(5);
return view('admin.membres.index', compact('membres'))
->with('i', (request()->input('page', 1)-1)*5);
}
In my index.blade I have this
#foreach($membres as $membre)
<tr>
<td> {{$membre->name_membre}}</td>
<td> {{$membre->fk_club}}</td>
<td>
<form method="POST" action="{{ route('membres.destroy', $membre) }} ">
<a class="btn btn-sm btn-warning" href="{{route('membres.edit',$membre->id_membre)}}">Editer</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-sm btn-danger">Deleter</button>
</form>
</td>
</tr>
#endforeach
Thank you for your help.
On your Membre Model Add this
class Membre extends Model{
//
protected $fillable = ['name_membre', 'fk_club'];
public function club(){
return $this->belongsTo('App\Club', 'fk_club');
}
}
You can get this data on your view file by
<td> {{$membre->club->name_club}}</td>
And your Club Model add this
class Club extends Model{
public function membre(){
return $this->hasMany('App\Membre', 'fk_club','id_club');
}
}
First of all, your foreign key in the members migration references id_client in the clients table, you probably want that to reference id_club in the clubs table (unless your table is actually called clients).
Then to get the name of the club a member belongs to, you'll have to add a function called club to your Membre model, which returns something like $this->belongsTo('App\Club');. If you haven't done so, you should also add a members function to your Club model, which returns something like $this->hasMany('App\Membre');.
In your view you can access the name of the club with $membre->club->name_club.
Here's a link to the Laravel documentation about Eloquent relationships, maybe that helps clearing things up.
You need to define your relation,
class Membre extends Model
{
//
protected $fillable = ['name_membre', 'fk_club'];
public function club()
{
return $this->belongsTo('App\Club', 'fk_club');
}
}
Now you can use this like below,
<td> {{$membre->club->name_club}}</td>

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