laravellaravel-8voyager

Search in Laravel voyager related table


There is 2 table for managing categories one for parents and another for sub-categories. When I want to search with this associated field, I can't. and get this error

Error description

  1. Hizmetler Model (Sub-category):
    class Hizmetler extends Model
    {
        protected $primaryKey = 'hizmet_id';
        protected $table = 'hizmetler';
        public $incrementing = false;
    
        use SoftDeletes;
        protected $dates = ['deleted_at'];
        public function Hizmetler(){
            return $this->belongsTo(Hizmetler::class,'hizmet_ust_kategori');
        }
    }
  1. UstKategori Model (Parent category):
    class UstKategori extends Model
    {
        protected $primaryKey = 'id';
        protected $table = 'ust_kategori';
        public $incrementing = false;
    
        use SoftDeletes;
        protected $dates = ['deleted_at'];
        public function UstKategori(){
            return $this->hasOne(UstKategori::class);
        }
    }

Category Table Sub Categroy Table


Solution

  • Your relationship is incorrect. according to your case, the relationship between the categories and their child is One to Many.

    Parent Model:

    class UstKategori extends Model
    {
        public function childs(){
            return $this->hasMany(Hizmetler::class, 'hizmet_ust_kategori');
        }
    }
    

    Child Model:

    class Hizmetler extends Model
    {
        public function parent(){
            return $this->belongsTo(UstKategori::class, 'hizmet_ust_kategori');
        }
    }
    

    You can read the documentation and examples here: https://laravel.com/docs/9.x/eloquent-relationships#one-to-many