Laravel Has Many Through Eloquent Relationship Example

Today, We want to share with you Laravel Has Many Through Eloquent Relationship Example.In this post we will show you laravel has many through pivot table, hear for laravel has many through relationship example we will give you demo and example for implement.
In this post, we will learn about has_many through relationship laravel 5 with an example.

Laravel Has Many Through Eloquent Relationship Demo

Let’s start I have to make the Laravel migration of “employees”, “Articles” and “students” database table. I shall also put the simple main foreign key with employees and Articles table in database. so let’s make a simple Example of the Laravel Has Many Through Eloquent Relationship like as below:

READ :  Generate PDF HTML in LARAVEL DOMPDF

Create Migrations:

employees table migration:
[php]
Schema::create(’employees’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘name’);
$table->string(’email’)->unique();
$table->string(‘password’);
$table->integer(‘student_id’)->unsigned();
$table->rememberToken();
$table->timestamps();
$table->foreign(‘student_id’)->references(‘id’)->on(‘students’)
->onDelete(‘cascade’);
});
[/php]
Articles table migration:
[php]
Schema::create(‘Articles’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(“name”);
$table->integer(’employee_id’)->unsigned();
$table->timestamps();
$table->foreign(’employee_id’)->references(‘id’)->on(’employees’)->onDelete(‘cascade’);
});
[/php]
students table migration:
[php]
Schema::create(‘students’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘name’);
$table->timestamps();
});
[/php]

Make Models:

Now, I shall make a simple Student model. I shall also main use “hasManyThrough()” for some Laravel relationship of both model.

Student Model:
[php]
hasManyThrough(
Post::class,
User::class,
‘student_id’, // Foreign key on employees table…
’employee_id’, // Foreign key on Articles table…
‘id’, // Local key on students table…
‘id’ // Local key on employees table…
);
}
}
[/php]

READ :  Angular Autocomplete multiple Tags value

Retrieve Records:

[php]
$Student = Student::find(1);
dd($Student->Articles);
[/php]

jQuery 15 Powerful Tips and Tricks for Developers and Web Designer

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about laravel 5 hasmany through relation.
I would like to have feedback on my Infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.

Leave a Comment