Home > Back-end >  Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo
Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo

Time:03-29

I get this error Undefined property:

Illuminate\Database\Eloquent\Relations\BelongsTo::$name (View: C:\xampp\htdocs\ESchool\resources\views\front\index.blade.php)

and I don not know what is wrong

this is the part of my index page where I get the error <

div >
                        <a href="../../../../../../Users/Khaldoun Alhalabi/Desktop/etrain/course-details.html"
                            >{{$course->categories()->name}}</a>

and here my 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 $primaryKey = "id" ;
    public $timestamps = true ;
    protected $fillable =
    [
        'name' ,
    ] ;


    /**
     * Get all of the comments for the Category
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function courses()
    {
        return $this->hasMany(Course::class, 'foreign_key');
    }
}

and here my course model

    <?php

namespace App\Models;

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

class Course extends Model
{
    use HasFactory;
    protected $table = "courses"  ;
    protected $primaryKey = "id" ;
    public $timestamps = true ;
    protected $fillable =
    [
        'name' ,
        'image' ,
        'price' ,
        'small_description' ,
        'description' ,

    ] ;
  public function categories()
    {
        return $this->belongsTo(Category::class);
    }
    public function trainers()
    {
        return $this->belongsTo(Trainer::class);
    }
    public function students()
    {
        return $this->belongsTo( Student::class );
    }
}

CodePudding user response:

  1. Change public function categories() to public function category()
    (same for the the other functions. BelongsTo returns one object, so the function names should be singular)
  2. I don't see a category_id in your model, but I am going to assume it is there.
  3. Don't use brackets when accessing the related object's properties, just write
    $course->category->name

CodePudding user response:

I Solved it the problem was in the name of the foreign key I was named it as cat_id but it must be category_id found it in the docs of laravel https://laravel.com/docs/9.x/eloquent-relationships#one-to-many

  • Related