7

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();
        });
    }
Emre Ensar Çapcı
  • 107
  • 1
  • 1
  • 4

8 Answers8

8

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');
}
mrdev
  • 617
  • 7
  • 8
4

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

$new->category->name ?? None'
abdennour
  • 43
  • 3
3

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.
Bonestorm
  • 119
  • 1
  • 6
2
<td>{{ $new->category->name ?? 'None' }}</td>
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • Welcome to Stack Overflow! Please read [answer] and [edit] your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post. – Adriaan Sep 28 '22 at 14:15
1

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.

rameezmeans
  • 830
  • 1
  • 10
  • 21
0

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.

ZygD
  • 22,092
  • 39
  • 79
  • 102
0

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

Hamidreza
  • 139
  • 1
  • 12
0

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