Reputation: 3
I have 2 table, which is posts and categories. The relationship between posts and categories is many to one. So the code in post class model is like this :
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function category()
{
return $this->belongsTo(Category::class);
}
}
With that code the application running successfully.
The problem is, when i tried to change the category function name to categories, and i tried to access the name of category of the post like this :
Post::first()->categories->name
, laravel give an error like this Attempt to read property "name" on null in D:\BelajarProgram\CODINGAN\Laravel\application\coba-laraveleval()'d code.
(edited
the "Post::first()->category" return the category of the post when the eloquent function name is category. But when i tried to change the name of function like categories and accessing it with "Post::first()->categories", it return a null
)
I have tried to change the name of the function of eloquent relationship in category class model with random name, but i still can accessing it and laravel doesn't give an error. The code of category class model is like this
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
protected $guarded = ['id'];
public function posts(){
return $this->hasMany(Post::class);
}
}
Can someone help me, why i can change the name of eloquent function in category class model, but can't in post class model ?
Upvotes: 0
Views: 133
Reputation: 1423
Doing the following should work:
public function categories()
{
return $this->belongsTo(Category::class, 'category_id', 'id');
}
Let me know if it works or not.
Upvotes: 0