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:
- Change
public function categories()
topublic function category()
(same for the the other functions. BelongsTo returns one object, so the function names should be singular) - I don't see a category_id in your model, but I am going to assume it is there.
- 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