@alien32 May be your login session has expired. Login again and check
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!');
}
}
@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',
]);
}
Please or to participate in this conversation.