Emre Ensar Çapcı
Emre Ensar Çapcı

Reputation: 137

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)
                        <a href="{{url('storage/images/'.$new->photo)}}" target="_blank" class="btn btn-sm btn-secondary">Görüntüle</a></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();
        });
    }

Upvotes: 9

Views: 104678

Answers (8)

Murtaza Noori
Murtaza Noori

Reputation: 91

You can fix this Easily But Putting a Condition Such as :

<td> $bew->category?$item->category->name:'-' </td>

this code will firstly go to your variable and access your Data , and if theres something wrong in your database then it will display you a - instead , so you can know theres a problem in ur DB

Upvotes: 0

Bonestorm
Bonestorm

Reputation: 339

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.

Upvotes: 11

Ignacio Gzzz
Ignacio Gzzz

Reputation: 29

<td>{{ $new->category->name ?? 'None' }}</td>

Upvotes: 2

Hamidreza
Hamidreza

Reputation: 148

Such an ID may not exist. Check the ID column once

Upvotes: 0

abdennour
abdennour

Reputation: 63

I had the same problem , and i solve it by this :

$new->category->name ?? None'

Upvotes: 6

user3078963
user3078963

Reputation: 1

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.

Upvotes: 0

rameezmeans
rameezmeans

Reputation: 850

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.

Upvotes: 1

mrdev
mrdev

Reputation: 647

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

Upvotes: 9

Related Questions