How to create a one-to-many relationship in Laravel Eloquent?
Oct 12, 2025 am 12:16 AMSet up the database with a foreign key in the "many" table (e.g., posts.user_id). 2. Use hasMany in the "one" model (User) to define the relationship. 3. Use belongsTo in the "many" model (Post) for the inverse. 4. Access related data via $user->posts or $post->user, and create records using $user->posts()->create().
To create a one-to-many relationship in Laravel Eloquent, you define the relationship in your model classes using Eloquent's built-in methods. This is commonly used when one record (e.g., a user) owns multiple related records (e.g., posts).
Define the Database Tables
Ensure your database schema supports the relationship. For example, if a User has many Posts, the posts
table should have a user_id
foreign key.
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('user_id'); $table->string('title'); $table->text('content'); $table->timestamps(); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); });
Create the Eloquent Models
Create models for both entities if they don’t exist:
php artisan make:model User
php artisan make:model Post
Define the Relationship in Models
In the User model (the "one" side), use the hasMany
method:
class User extends Model { public function posts() { return $this->hasMany(Post::class); } }
In the Post model (the "many" side), define the inverse using belongsTo
:
class Post extends Model { public function user() { return $this->belongsTo(User::class); } }
Using the Relationship
Once set up, you can access related data easily:
- Get all posts for a user:
$user->posts
- Get the user who owns a post:
$post->user
- Create a post for a user:
$user->posts()->create($request->validated())
Basically just set up the foreign key, define hasMany
on the parent and belongsTo
on the child, and Eloquent handles the rest.
The above is the detailed content of How to create a one-to-many relationship in Laravel Eloquent?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

LaravelusesMonologtologmessagesviatheLogfacade,withdefaultlogsstoredinstorage/logs/laravel.log.Configurechannelsinconfig/logging.phptocontroloutput;thedefaultstackchannelaggregatesmultiplehandlerslikesingle,whichwritestoafile.UseLog::info(),Log::warn

InstallLaravelSanctumviaComposerandpublishitsfiles,thenrunmigrations.2.AddtheHasApiTokenstraittotheUsermodel.3.Definelogin,logout,anduserroutesinapi.php,usingSanctum’sauth:sanctummiddleware.4.ProtectAPIroutesbyapplyingtheauth:sanctummiddleware.5.Incl

ACountrycanaccessallPoststhroughUsersusinghasManyThrough.Forexample,withcountries,users,andpoststableslinkedbyforeignkeys,theCountrymodeldefinesahasManyThroughrelationshiptoPostviaUser,enablingefficientindirectdataretrievalacrosstwoone-to-manyrelatio

Laravel resource controller quickly processes CRUD operations through RESTful routing, uses the Artisan command to generate controllers and register resource routes, and can create all standard routes in a single line of code, which supports restriction of actions, adding middleware and naming, and combines routing model binding to automatically parse parameters, improve development efficiency and keep the code structure clear.

ToimplementAPIauthenticationwithLaravelSanctum,youneedtosetuptoken-basedauthenticationthatallowsSPAs,mobileapps,andthird-partyservicestosecurelyaccessyourAPI.SanctumprovidesalightweightapproachbyissuingAPItokensthatcan

Use the redirect() helper function to realize redirection in the Laravel controller, such as redirect()->route('home') to jump to the named route, redirect('/dashboard') to the specified URL, redirect()->back() returns to the previous page, and use withInput() to retain form data and with() to pass session messages. It is recommended to use named routes to improve maintainability.

Use the DB facade to execute native SQL, select DB::select, DB::insert, DB::update or DB::delete according to the query type, and use parameter binding to prevent SQL injection; DB::unprepared can be used for structural changes; combined with DB::raw, native expressions can be embedded in the query constructor.

Configure the second database connection: add a new connection in config/database.php and set the .env variable; 2. Use DB::connection('mysql_second') or the model $connection attribute to specify the connection; 3. Use the on() method to switch dynamically during runtime; 4. Use Schema::connection() and cooperate with the --database option to execute during migration.
