Updated 27 November 2023
Hello guys, So in this article we will learn how to use One To Many Relationships in Laravel. In Laravel, relationships are defined within the model classes. Let’s consider a scenario where we have a User model and a Post model. A user can have multiple posts, so we’ll set up a one-to-many relationship between them.
1 |
composer create-project laravel/laravel --prefer-dist laravel |
1 |
php artisan make:model Post -m |
The above command will create a Post model inside the app/Models folder and a migration file inside the database/migration folder.
Now you can update your User model, Post model, and migration files accordingly as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use Laravel\Sanctum\HasApiTokens; use Illuminate\Database\Eloquent\Relations\HasMany; class User extends Authenticatable { use HasApiTokens, HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for serialization. * * @var array<int, string> */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast. * * @var array<string, string> */ protected $casts = [ 'email_verified_at' => 'datetime', 'password' => 'hashed', ]; /** * Get the all user posts. */ public function posts(): HasMany { return $this->hasMany(Post::class); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class Post extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array<int, string> */ protected $fillable = [ 'title', 'body', 'user_id', ]; /** * Get the user that owns the post. */ public function user(): BelongsTo { return $this->belongsTo(User::class); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { /** * Run the migrations. */ public function up(): void { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('body'); $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('posts'); } }; |
1 2 3 |
php artisan make:seeder UsersTableSeeder php artisan make:seeder PostsTableSeeder |
Now update your both seeder as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; class UsersTableSeeder extends Seeder { /** * Run the database seeds. */ public function run(): void { DB::table('users')->insert([ [ 'name' => 'John Doe', 'password' => Hash::make('password123'), ], [ 'name' => 'Jane Smith', 'password' => Hash::make('password456'), ], ]); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class PostsTableSeeder extends Seeder { /** * Run the database seeds. */ public function run(): void { $faker = \Faker\Factory::create(); for ($i = 1; $i <= 10; $i++) { DB::table('posts')->insert([ 'title' => $faker->sentence, 'body' => $faker->paragraph, 'user_id' => rand(1, 2), // Assuming user IDs 1 and 2 exist in the users table ]); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php namespace Database\Seeders; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. */ public function run(): void { $this->call([ UsersTableSeeder::class, PostsTableSeeder::class ]); } } |
Now run the below command
1 |
php artisan db:seed |
1 |
php artisan make:controller PostController |
Now update PostController like the below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php namespace App\Http\Controllers; use App\Models\User; use App\Models\Post; class PostController extends Controller { public function users() { // Get user along with his post. $user = User::with('posts')->find(1); // suppose user id is (1). /* Let's suppose you want to get user post then you have to use $post->users */ return response()->json($user); } public function posts() { // Get post along with his user. $post = Post::with('users')->find(2); // Suppose post id is (2). /* Let's suppose you want to get user email then you have to use $post->users->name */ return response()->json($post); } } |
For that simply go to web.php inside the Routes folder and update the file like below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\PostController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider and all of them will | be assigned to the "web" middleware group. Make something great! | */ Route::get('/users', [PostController::class, 'users']); Route::get('/posts', [PostController::class, 'posts']); |
Now simply run the below command.
1 |
php artisan serve |
Now you can simply check the output in the browser by hitting the above routes.
Thank you for reading this tutorial. We hope you found it helpful. If you have any questions or encounter any issues, please feel free to leave a comment below.
Additionally, if you’re looking to hire Laravel developers, you can visit the Hire Laravel Developer page. This platform provides a pool of experienced Laravel developers who can help you with your project requirements and ensure the successful implementation of your ideas.
Furthermore, if you’re interested in enhancing the functionality of Bagisto, you can check out the Extensions page on the official Bagisto website. This page showcases a wide range of extensions that can be integrated into your Bagisto e-commerce platform to add new features, improve user experience, and optimize your online store’s performance.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
2 comments
Thank you so much for the appreciation
Stay Tune..!!