如何在Laravel中使用雄辩
创建模型和迁移:使用 php artisan make:model Post -m 生成模型和迁移文件,定义表结构后运行 php artisan migrate;2. 基本CRUD操作:通过 Post::all()、find()、create()、save() 和 delete() 方法实现数据的查询、创建、更新和删除;3. 使用Eloquent关联:在模型中定义 belongsTo 和 hasMany 关系,并通过 with() 方法实现关联数据的预加载以避免N 1查询问题;4. Eloquent查询:利用查询构造器链式调用如 where、orderBy 等方法,并通过局部作用域 scopePublished 复用查询逻辑;5. 批量赋值保护:在模型中设置 $fillable 或 $guarded 属性以防止意外赋值;6. 软删除:引入 SoftDeletes trait 并在迁移中添加 softDeletes(),使用 delete() 和 restore() 控制软删除与恢复;7. 访问器与修改器:通过 setTitleAttribute 和 getTitleAttribute 在设置或获取属性时自动处理数据格式。Eloquent通过模型与数据库交互,使开发者无需编写原生SQL即可高效操作数据,建议每张表对应一个模型,合理定义关联关系并充分利用Eloquent提供的功能完成数据操作,最终实现清晰、可维护的代码结构。
Eloquent is Laravel’s built-in ORM (Object-Relational Mapper) that makes it easy to interact with your database using PHP syntax instead of writing raw SQL. It’s powerful, expressive, and beginner-friendly once you understand the basics. Here’s how to use Eloquent effectively in Laravel.

1. Creating Models and Migrations
Every database table has a corresponding Eloquent model. To create a model along with a migration, run:
php artisan make:model Post -m
This creates:

app/Models/Post.php
(the model)database/migrations/xxxx_xx_xx_create_posts_table.php
(the migration)
In the migration file, define your table structure:
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->foreignId('user_id')->constrained(); $table->timestamps(); });
Run the migration:

php artisan migrate
Now you can use the Post
model to interact with the posts
table.
Note: If your model is in a folder like
Models
, make sure to reference it correctly or update the default namespace inconfig/auth.php
if needed.
2. Basic CRUD Operations
Once your model is set up, you can perform basic operations.
Retrieve All Records
$posts = Post::all();
Find a Record by ID
$post = Post::find(1); // or throw an exception if not found $post = Post::findOrFail(1);
Create a New Record
Post::create([ 'title' => 'My First Post', 'content' => 'Hello World', 'user_id' => 1, ]);
Or manually:
$post = new Post(); $post->title = 'Another Post'; $post->content = 'More content'; $post->user_id = 1; $post->save();
Update a Record
$post = Post::find(1); $post->title = 'Updated Title'; $post->save();
Or use mass update:
Post::where('id', 1)->update(['title' => 'Updated']);
Delete a Record
$post = Post::find(1); $post->delete(); // or delete directly Post::destroy(1);
3. Using Eloquent Relationships
Eloquent makes defining relationships between models simple.
Define a Relationship (e.g., Post belongs to User)
In the Post
model:
public function user() { return $this->belongsTo(User::class); }
In the User
model:
public function posts() { return $this->hasMany(Post::class); }
Now you can access related data:
$post = Post::with('user')->find(1); echo $post->user->name; // Access the author $user = User::find(1); foreach ($user->posts as $post) { echo $post->title; }
Use
with()
to eager load relationships and avoid N 1 query problems.
4. Querying with Eloquent
Eloquent models extend the query builder, so you can chain methods:
$publishedPosts = Post::where('status', 'published') ->where('created_at', '>', now()->subDays(7)) ->orderBy('created_at', 'desc') ->get();
Scopes (Reusable Queries)
Define a local scope in your model:
public function scopePublished($query) { return $query->where('status', 'published'); }
Use it:
$posts = Post::published()->get();
5. Mass Assignment Protection
To use create()
or update()
safely, define fillable or guarded fields.
In your model:
protected $fillable = ['title', 'content', 'user_id'];
Or, alternatively:
protected $guarded = []; // allows all, but less secure
6. Soft Deletes (Optional)
To "delete" records without removing them from the database:
- Add
use Illuminate\Database\Eloquent\SoftDeletes;
to your model. - Add
$table->softDeletes();
in your migration. - Then use
->delete()
— it setsdeleted_at
instead of removing the row.
Restore a soft-deleted record:
$post = Post::withTrashed()->find(1); $post->restore();
7. Accessors and Mutators
Modify data when getting or setting attributes.
Mutator (set)
public function setTitleAttribute($value) { $this->attributes['title'] = ucfirst($value); }
Accessor (get)
public function getTitleAttribute($value) { return ucfirst($value); }
Now every time you get or set title
, it's capitalized.
Eloquent makes working with databases in Laravel intuitive and clean. Start with models and basic queries, then gradually use relationships, scopes, and accessors as your app grows. Most of the time, you won’t need raw SQL.
Basically, just remember: one model per table, define relationships, and let Eloquent do the heavy lifting.
以上是如何在Laravel中使用雄辩的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undress AI Tool
免费脱衣服图片

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Stock Market GPT
人工智能驱动投资研究,做出更明智的决策

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

laravelleloquentsuportsubqueriesInSelect,从哪里,andorderbyClauses启用Feflexibledataretievalwithoutrawsql; 1.UseselectSub()toaddcompentedColumnSlumnsLikePostCountCountCountCountCountPeruser; 2.Usefromsub; 2.usefromsub; 2.Usefromsub orclosolusoblesoblesoboledInfom()

InstallLaravelCashierviaComposerandconfiguremigrationandBillabletrait.2.CreatesubscriptionplansinStripeDashboardandnoteplanIDs.3.CollectpaymentmethodusingStripeCheckoutandstoreitviasetupintent.4.SubscribeusertoaplanusingnewSubscription()anddefaultpay

定义调度:在App\Console\Kernel类的schedule方法中使用Schedule对象配置Artisan命令调度;2.设置频率:通过everyMinute、daily、hourly等链式方法或cron语法设定执行频率;3.传递参数:使用数组或字符串向命令传递参数;4.调度Shell命令:使用exec方法运行系统命令;5.添加条件:使用when、weekdays等方法控制执行时机;6.输出处理:使用sendOutputTo、appendOutputTo或emailOutputTo记录或

SoftdeletesinLaravelallowyoutomarkrecordsasdeletedwithoutremovingthemfromthedatabasebysettingadeleted_attimestamp,whichenablesdatarecoverywhenneeded.1.AddtheSoftDeletestraittoyourmodel:importanduseIlluminate\Database\Eloquent\SoftDeletesinyourmodelcl

使用字符串字段和PHP枚举是Laravel中处理枚举的最佳方式。1.在迁移中使用string类型字段并可选添加checkIn约束;2.定义带有字符串backing值的PHP枚举(PHP8.1 );3.在模型中通过$casts将字段自动转换为枚举实例;4.在表单验证中使用Rule::in(Enum::values())确保输入合法;5.在工厂和种子文件中使用Enum::cases()或fake()->enum()生成测试数据;6.查询时使用枚举的->value属性或直接比较枚举实例。该

创建模型和迁移:使用phpartisanmake:modelPost-m生成模型和迁移文件,定义表结构后运行phpartisanmigrate;2.基本CRUD操作:通过Post::all()、find()、create()、save()和delete()方法实现数据的查询、创建、更新和删除;3.使用Eloquent关联:在模型中定义belongsTo和hasMany关系,并通过with()方法实现关联数据的预加载以避免N 1查询问题;4.Eloquent查询:利用查询构造器链式调用如where

PolymorphicrelationshipsinLaravelallowamodellikeCommentorImagetobelongtomultiplemodelssuchasPost,Video,orUserusingasingleassociation.2.Thedatabaseschemarequires{relation}_idand{relation}_typecolumns,exemplifiedbycommentable_idandcommentable_typeinaco

UseMail::fake()orNotification::fake()tomockfacadesandassertsentmessageswithoutrealsideeffects.2.Forcustomserviceclasses,useMockery::mock()with$this->instance()toinjectmockeddependenciesanddefineexpectedbehaviorlikeshouldReceive('method')->andRe
