Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

FUUU's avatar
Level 1

Attempt to read property "name" on null

hello everyone, recently i've caught this error. My $book->category->name return to a null even though it was running nomally before

book model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Book extends Model
{
    use HasFactory;
    protected $table = 'tbl_book';
    protected $primaryKey = 'IDbook';
    protected $fillable = [
        'IDbook',
        'category_id',
        'IDauthor',
        'bookname',
        'small_descript',
        'descript',
        'img',
        'trending',
        'status',
    ];

    public function category()
    {
        return $this->belongsTo(Category::class, 'IDbook', 'id');
    }
}

category model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    use HasFactory;

    protected $table = 'categories';

    protected $fillable = [
        'name',
        'category_slug',
        'description',
        'image',
        'status',
    ];

    public function book()
    {
        return $this->hasMany(Book::class, 'category_id', 'IDbook');
    }
}

book index

                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Name</th>
                                            <th>Category</th>
                                            {{-- <th>Author</th> --}}
                                            <th>Small Description</th>
                                            <th>Description</th>
                                            <th>Image</th>
                                            <th>Status</th>
                                            <th>Trending</th>
                                            <th>Action</th>
                                        </tr>
                                        <tbody>
                                            @foreach ($books as $book)
                                                <tr>
                                                    <td>{{ $book->IDbook }}</td>
                                                    <td>{{ $book->bookname }}</td>
                                                    <td>{{ $book->category->name }}
                                                        {{-- @if ($book->category)
                                                            
                                                        @else
                                                            No category
                                                        @endif --}}
                                                    </td>
                                                    {{-- <td>{{ $book->author->name }}</td> --}}
                                                    <td>{{ $book->small_descript }}</td>
                                                    <td>{{ $book->descript }}</td>
                                                    <td><img style="width: 2cm; height: 2cm;" src="{{ URL::to('/uploads/book/'.$book->img) }}" alt=""></td>
                                                    <td>{{ $book->status == '1' ? 'Hidden':'Visible'}}</td>
                                                    <td>{{ $book->trending == '1' ? 'Hidden':'Visible'}}</td>
                                                    <td>
                                                        <a href="{{ url('admin/book/'.$book->IDbook.'/edit') }}" class="btn btn-success">Edit</a>
                                                        <a href="#" wire:click="deleteBook({{$book->IDbook}})" data-bs-toggle="modal" 
                                                            data-bs-target="#deleteModal" class="btn btn-danger">Delete</a>
                                                    </td>
                                                    <td>{{ $book->action }}</td>
                            
                                                </tr>
                                                
                                            @endforeach
                                            {{ $books->links('pagination::bootstrap-5') }} 
                                        </tbody>
                                    </thead>
                                </table>

bookcontroller using dd($book->category) and it return null

<?php

namespace App\Http\Controllers\Admin;
use App\Http\Requests\BookFormRequest;
use App\Http\Controllers\Controller;
use App\Models\Author;
use App\Models\Category;
use App\Models\Book;
use Illuminate\Support\Facades\File;

class BookController extends Controller
{
    public function index()
    {
        $books = Book::all();
        return view('admin.book.index', compact('books'));
    }

    public function render()
    {
        $books = Book::orderBy('id', 'DESC')->paginate(3);
        return view('admin.book.index', ['books' => $books]);
    }

    public function create()
    {
        $categories = Category::all();
        $authors = Author::all();
        return view('admin.book.create', compact('categories','authors'));
    }

    public function store(BookFormRequest $request)
    {
        
        $validatedData = $request->validated();
        $book = new Book;
        $book->IDbook = $validatedData['IDbook'];
        $book->category_id = $validatedData['category_id'];
        $book->IDauthor = $validatedData['IDauthor'];
        $book->bookname = $validatedData['bookname'];
        $book->small_descript = $validatedData['small_descript'];
        $book->descript = $validatedData['descript'];
        if($request->hasFile('img')) {
            $file = $request->file('img');
            $ext = $file->getClientOriginalExtension();
            $filename = time().'.'.$ext;

            $file->move('uploads/book', $filename);
            
            $book->img = $filename;
        }
        
        $book->status = $request->status == true ? '1':'0';
        $book->trending = $request->status == true ? '1':'0';
        $book->save();

        return redirect('admin/book')->with('message', 'Book add successfully!');
        
    }


    public function edit(int $IDbook)
    {
        $categories = Category::all();
        $authors = Author::all();
        $book = Book::findOrFail($IDbook);
        return view('admin.book.edit', compact('categories','authors', 'book'));
    }

    public function update(BookFormRequest $request, $IDbook)
    {
        $book = Book::findOrFail($IDbook);
        $validatedData = $request->validated();
        $book->IDbook = $validatedData['IDbook'];
        $book->category_id = $validatedData['category_id'];
        $book->IDauthor = $validatedData['IDauthor'];
        $book->bookname = $validatedData['bookname'];
        $book->small_descript = $validatedData['small_descript'];
        $book->descript = $validatedData['descript'];
        if($request->hasFile('img')) {
            $path = 'upload/book/'.$book->img;
            if(File::exists($path)) {
                File::delete($path);
            }

            
            $file = $request->file('img');
            $ext = $file->getClientOriginalExtension();
            $filename = time().'.'.$ext;

            $file->move('uploads/book', $filename);
            
            $book->img = $filename;
            
        }
        
        $book->status = $request->status == true ? '1':'0';
        $book->trending = $request->trending == true ? '1':'0';
        $book->update();

        return redirect('admin/book/')->with('message', 'Update successfully!');
    }
}
0 likes
10 replies
shariff's avatar

@FUUU Did you login again? check whether your able to get the relationship dd($book->category)

shariff's avatar

@FUUU what is the result of dd($book->category) Or try this

{{ $book->category ? $book->category->name : " " }}
FUUU's avatar
Level 1

@shariff it return

App\Models\Category {#1444 ▼ // resources\views/livewire/admin/book/index.blade.php
  #connection: "mysql"
  #table: "categories"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: array:8 [▶]
  #original: array:8 [▶]
  #changes: []
  #casts: []
  #classCastCache: []
  #attributeCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: array:5 [▶]
  #guarded: array:1 [▶]
}
shariff's avatar

@FUUU After adding this condition {{ $book->category ? $book->category->name : " " }} also your getting the same error?

FUUU's avatar
Level 1

@shariff i already try this with if else statement, and it just cover my bug and my category name doesn't display

tykus's avatar
tykus
Best Answer
Level 104

@fuuu you are looping over a Collection of Book instances, right? So, most likely one or more of the Books in the Collection has no Category either because the category_id is not valid; or is null. The way to mitigate for this are (i) referential integrity at database level (i.e. category_id references id on categories) or (ii) checks in PHP {{ $book->category?->name }}.

You also can define the relationship with a fallback:

public function category()
{
    return $this->belongsTo(Category::class)->withDefault([
        'name' => 'Unknown Category',
    ]);
}
2 likes
FUUU's avatar
Level 1

@tykus it work! surprising that I couldn't find this when I searched for my error, thank you for helping me!

Please or to participate in this conversation.