search

Home  >  Q&A  >  body text

Laravel Eloquent associated function name

<p>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: </p> <pre class="brush:php;toolbar:false;"><?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Post extends Model { use HasFactory; protected $guarded = ['id']; public function category() { return $this->belongsTo(Category::class); } }</pre> <p>Using this code, the application runs successfully. </p><p>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: </p><p> <code>Post::first()->categories->name</code>, laravel give an error like this <code>Attempt to read property "name" on null in D:BelajarProgramCODINGANLaravelapplicationcoba-laraveleval() 'd code.</code></p> <p>(edited</p> <p>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. </p> <p>)</p> <p>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: </p> <pre class="brush:php;toolbar:false;"><?php namespace AppModels; use IlluminateDatabaseEloquentFactoriesHasFactory; use IlluminateDatabaseEloquentModel; class Category extends Model { use HasFactory; protected $guarded = ['id']; public function posts(){ return $this->hasMany(Post::class); } }</pre> <p>Can anyone help me? Why can I change the Eloquent function name in the category class model but not in the posts class model? </p>
P粉729198207P粉729198207496 days ago412

reply all(1)I'll reply

  • P粉330232096

    P粉3302320962023-07-24 00:30:50

    Doing the following should solve the problem:

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

    reply
    0
  • Cancelreply