0

How can we use common relations in laravel to write in a single file and extend that class in a model where we required that relations.

Please have a look at model "Court":

use Illuminate\Database\Eloquent\Model;
use Astrotomic\Translatable\Translatable;
use TranslatableContract;

class Court extends Model implements TranslatableContract
{
    use Translatable;
    public $translatedAttributes = ['title', 'description'];
    public $fillable = ['court_type_id', 'state_id', 'city_id'];

    public function courtType()
    {
        return $this->belongsTo('App\CourtType', 'court_type_id');
    }

    public function state()
    {
        return $this->belongsTo('App\State');
    }

    public function city()
    {
        return $this->belongsTo('App\City');
    }
}

another model "CourtCase"

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Astrotomic\Translatable\Translatable;
use TranslatableContract;

class CourtCase extends Model implements TranslatableContract
{
    use Translatable;
    public $translatedAttributes = ['case_id', 'title', 'description'];
    public $fillable = ['court_id', 'state_id', 'city_id'];

    public function userable()
    {
        return $this->morphTo();
    }

    public function images()
    {
        return $this->morphMany('App\Image', 'imageable');
    }

    public function state()
    {
        return $this->belongsTo('App\State');
    }

    public function city()
    {
        return $this->belongsTo('App\City');
    }
}

Here in above models we have two relations named as city, state that are common in each model which allow code repetition so how can we write these relations in a single file and extend that in particular model.

nayan verma
  • 103
  • 1
  • 11

1 Answers1

0

Create a new custom model base that extends the default model class:

namespace App;
use Illuminate\Database\Eloquent\Model;

class CustomModelBase extends Model {

public function find() {
   // Your custom find functionality goes here.
 }

  // etc
 }

For all of your app models, instead of extending model, extend your new custom model base class.

namespace App;

class Post extends CustomModelBase {
}
Rushikesh Ganesh
  • 290
  • 2
  • 16