Skip to main content

Posts

Showing posts with the label relationships in laravel

has, whereHas,whereRelation condition on realtionship tables in laravel

 I  will give you very simple example of how to use wherehas condition with laravel eloquent relationship. you can also use with laravel 6, laravel 7, laravel 8 and laravel 9 version. Sometime we need to add where condition with relation table then you need to use wherehas() method. for example if you have users with country relation then you want to filter with country then you must have to use whereHas(). so here i will give you two way to add condition with relation model, one using whereHas and second using whereRelation().

Realtionship in laravel with pivot table

Create Many2many relationship with pivot table   1. Create Factory with the specific model Using this query we can create factory class for specific model. php artisan make:factory ProjectFactory --model=Project 2. Create Seeder class Using this query we can create seeder class. php artisan make:seeder ProjectSeeder Write below code in this class in a run method in ProjectSeeder class public function run () {         factory ( Project :: class , 10 )-> create ();         foreach ( Project :: all () as $key => $project ) {             $users = User :: inRandomOrder ()-> take ( rand ( 1 , 3 ))-> pluck ( 'id' );             $project -> users ()-> attach ( $users );         } } 3. Create a relationship to the User model using Project Model. Inside Project Model public function users (){         return $this -> belongsTo...