I have two tables, namely "posts" and "categories". The relationship between "posts" and "categories" is many-to-one. Therefore, the code in the "Post" class model is as follows:
belongsTo(Category::class); } }
Using this code, the application runs successfully.
The problem is when I try to change the category function name to "categories" and I try to access the post's category name like this:
Post::first()->categories->name
, laravel give an error like this Attempt to read property "name" on null in D:BelajarProgramCODINGANLaravelapplicationcoba-laraveleval() 'd code.
(edited
When the Eloquent function name is "category", "Post::first()->category" returns the category of the post. However, when I try to change the function name to "categories" and access it using "Post::first()->categories", it returns null.
)
I tried changing the name of the Eloquent associated function in the category class model to a random name, but I can still access it and Laravel reports no errors. The code of the category class model is as follows:
hasMany(Post::class); } }
Can anyone help me? Why can I change the Eloquent function name in the category class model but not in the posts class model?
Doing the following should solve the problem: