Reputation: 153
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 class="special_cource_text">
<a href="../../../../../../Users/Khaldoun%20Alhalabi/Desktop/etrain/course-details.html"
class="btn_4">{{$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 );
}
}
Upvotes: 0
Views: 1886
Reputation: 153
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
Upvotes: 1
Reputation: 1072
public function categories()
to public function category()
$course->category->name
Upvotes: 1