Skip to content

Implementing Custom Eloquent Relations In Laravel * This repository is created for learning purpose only.

Notifications You must be signed in to change notification settings

iYogesharma/Relations

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Relations

This repository contains custom eloquent relations implemented in Laravel

Currently threre is only one relation called Belongs To Mnany Through. You can use it in model like any other eloquent relation.

    $this->belongsToManyThrough()

Example

Suppose you have three tables like :

    states
            id
            name
    
    cities 
            id 
            state_id 
            name 
            
    pincodes 
            id 
            pincode
            state_id

and you want to get all the pincodes of the state to which city belong. You can easily do this with belongsToManyThrough

* note You can do this simply by using existing eloquent relations like "$city->state->pincodes" but I tried to implement custom eloquent relation to do the same task in order to understand them better.

It's definitely not a good approach consider it only for learning purpose to understand Laravel eloquent relations better.

Inside the city model you can write :

    return $this->belongsToManyThrough( Pincode::class,State::class );
    

and in controller you can access it like

   City::find($id)->pincodes
   

or using eager loading

   City::with('pincodes')->find($id)
   

city has many pincodes through state

To use this relation you must use trait YS\Relations\Traits\HasRelationships in model you want to use this eloquent relation.

About

Implementing Custom Eloquent Relations In Laravel * This repository is created for learning purpose only.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages