Home > Back-end >  in laravel 8 I make simple relation between two model and after that when i get relation function no
in laravel 8 I make simple relation between two model and after that when i get relation function no

Time:05-25

I make simple relation between two model Offer(HasOne) and OfferType(belongTo). after that when i access relation function. function return below mention values

Offer model

class Offer extends BaseModel
{
    use HasFactory;

    protected $fillable = ['title', 'slug', 'type', 'offer_type_id', 'start_date', 'end_date', 'status'];

    public function offertype()
    {
        return $this->hasOne(OfferType::class);
    }
}

OfferType model

class OfferType extends BaseModel
{
    use HasFactory;

    protected $fillable = ['title', 'slug', 'image', 'status'];

    public function offer()
    {
        return $this->belongsTo(Offer::class, 'offer_type_id');
    }
}

Relation access in controller

 public function index()
    {
        $offers = Offer::all();
        dd($offers[0]->offertype());
        return view('admin.offers.index', compact('offers'));
    }

My Output

Illuminate\Database\Eloquent\Relations\HasOne {#263 ▼
  #foreignKey: "offer_types.offer_id"
  #localKey: "id"
  #query: Illuminate\Database\Eloquent\Builder {#1488 ▶}
  #parent: App\Models\Offer {#1499 ▶}
  #related: App\Models\OfferType {#1481 ▶}
  #isOneOfMany: false
  #relationName: null
  #oneOfManySubQuery: null
  #withDefault: null
}

CodePudding user response:

if offers 1 - 1 offer_types : foreignKey - offer_type_id

class Offer extends BaseModel
{
    use HasFactory;

    protected $fillable = ['title', 'slug', 'type', 'offer_type_id', 'start_date', 'end_date', 'status'];

    public function offertype()
    {
        return $this->belongsTo(OfferType::class);
    }
}

class OfferType extends BaseModel
{
    use HasFactory;

    protected $fillable = ['title', 'slug', 'image', 'status'];

    public function offer()
    {
        return $this->hasOne(Offer::class);
    }
}

CodePudding user response:

hi i think there is problem with you model relation

it should be like this

 public function offertype()
    {
        return $this->hasOne(OfferType::class,'offer_type_id','id');
    }

Then in your controller you can access like this

  $offers = Offer::with('offertype')->all();

i hope its works for you

  • Related