創(chuàng)建模型和遷移:使用php artisan make:model Post -m 生成模型和遷移文件,定義表結(jié)構(gòu)後運(yùn)行php artisan migrate;2. 基本CRUD操作:通過(guò)Post::all()、find()、create()、save() 和delete() 方法實(shí)現(xiàn)數(shù)據(jù)的查詢、創(chuàng)建、更新和刪除;3. 使用Eloquent關(guān)聯(lián):在模型中定義belongsTo 和hasMany 關(guān)係,並通過(guò)with() 方法實(shí)現(xiàn)關(guān)聯(lián)數(shù)據(jù)的預(yù)加載以避免N 1查詢問(wèn)題;4. Eloquent查詢:利用查詢構(gòu)造器鍊式調(diào)用如where、orderBy 等方法,並通過(guò)局部作用域scopePublished 復(fù)用查詢邏輯;5. 批量賦值保護(hù):在模型中設(shè)置$fillable 或$guarded 屬性以防止意外賦值;6. 軟刪除:引入SoftDeletes trait 並在遷移中添加softDeletes(),使用delete() 和restore() 控制軟刪除與恢復(fù);7. 訪問(wèn)器與修改器:通過(guò)setTitleAttribute 和getTitleAttribute 在設(shè)置或獲取屬性時(shí)自動(dòng)處理數(shù)據(jù)格式。 Eloquent通過(guò)模型與數(shù)據(jù)庫(kù)交互,使開發(fā)者無(wú)需編寫原生SQL即可高效操作數(shù)據(jù),建議每張表對(duì)應(yīng)一個(gè)模型,合理定義關(guān)聯(lián)關(guān)係並充分利用Eloquent提供的功能完成數(shù)據(jù)操作,最終實(shí)現(xiàn)清晰、可維護(hù)的代碼結(jié)構(gòu)。
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 (eg, 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中使用雄辯的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

熱AI工具

Undress AI Tool
免費(fèi)脫衣圖片

Undresser.AI Undress
人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Stock Market GPT
人工智慧支援投資研究,做出更明智的決策

熱門文章

熱工具

記事本++7.3.1
好用且免費(fèi)的程式碼編輯器

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

禪工作室 13.0.1
強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6
視覺(jué)化網(wǎng)頁(yè)開發(fā)工具

SublimeText3 Mac版
神級(jí)程式碼編輯軟體(SublimeText3)

創(chuàng)建模型和遷移:使用phpartisanmake:modelPost-m生成模型和遷移文件,定義表結(jié)構(gòu)後運(yùn)行phpartisanmigrate;2.基本CRUD操作:通過(guò)Post::all()、find()、create()、save()和delete()方法實(shí)現(xiàn)數(shù)據(jù)的查詢、創(chuàng)建、更新和刪除;3.使用Eloquent關(guān)聯(lián):在模型中定義belongsTo和hasMany關(guān)係,並通過(guò)with()方法實(shí)現(xiàn)關(guān)聯(lián)數(shù)據(jù)的預(yù)加載以避免N 1查詢問(wèn)題;4.Eloquent查詢:利用查詢構(gòu)造器鍊式調(diào)用如where

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

Yes,youcancreateasocialnetworkwithLaravelbyfollowingthesesteps:1.SetupLaravelusingComposer,configurethe.envfile,enableauthenticationviaBreeze/Jetstream/Fortify,andrunmigrationsforusermanagement.2.Implementcorefeaturesincludinguserprofileswithavatarsa

Laravel的TaskScheduling系統(tǒng)允許通過(guò)PHP定義和管理定時(shí)任務(wù),無(wú)需手動(dòng)編輯服務(wù)器crontab,只需在服務(wù)器添加一條每分鐘執(zhí)行一次的cron任務(wù):*cd/path-to-your-project&&phpartisanschedule:run>>/dev/null2>&1,隨後所有任務(wù)均在App\Console\Kernel類的schedule方法中配置;1.定義任務(wù)可使用command、call或exec方法,如$schedule-

創(chuàng)建語(yǔ)言文件:在resources/lang目錄下為每種語(yǔ)言(如en、es)創(chuàng)建子目錄並添加messages.php文件,或使用JSON文件存儲(chǔ)翻譯;2.設(shè)置應(yīng)用語(yǔ)言:通過(guò)中間件讀取請(qǐng)求頭Accept-Language或通過(guò)URL前綴檢測(cè)語(yǔ)言,使用app()->setLocale()設(shè)置當(dāng)前語(yǔ)言,並在Kernel.php中註冊(cè)中間件;3.使用翻譯函數(shù):在視圖中使用__(),trans()或@lang獲取翻譯內(nèi)容,推薦使用支持回退的__();4.支持參數(shù)和復(fù)數(shù):在翻譯字符串中使用佔(zhàn)位符如:n

使用Laravel構(gòu)建移動(dòng)端后端需先安裝框架並配置數(shù)據(jù)庫(kù)環(huán)境;2.在routes/api.php中定義API路由並使用資源控制器返回JSON響應(yīng);3.通過(guò)LaravelSanctum實(shí)現(xiàn)API認(rèn)證,生成令牌供移動(dòng)端存儲(chǔ)和認(rèn)證;4.處理文件上傳時(shí)驗(yàn)證文件類型並存儲(chǔ)至public磁盤,同時(shí)創(chuàng)建軟鏈接供外部訪問(wèn);5.生產(chǎn)環(huán)境需啟用HTTPS、設(shè)置限流、配置CORS、進(jìn)行API版本控制並優(yōu)化錯(cuò)誤處理,同時(shí)建議使用API??資源、分頁(yè)、隊(duì)列和API文檔工具以提升可維護(hù)性和性能。使用Laravel可構(gòu)建安全、可

LaraveluseMonologTologMessagesViathelogFacade,withDefaultLogSstoreDinstorage/logs/logaver.log.configurechannelsinconfig/loggpocontrolOlOutput; theDefeftoconTrolOutput; theDefeftStackChannAnneLagateSmultipleHersMultipleHerslikeSlikeSlikesingLikeSingLikeSingle,whatwrile.afile.usel.uselel.uselel.usecy.useleleel.use)

確保用戶表中存在remember_token列,Laravel默認(rèn)遷移已包含該字段,若無(wú)則通過(guò)遷移添加;2.在登錄表單中添加name為remember的複選框以提供“記住我”選項(xiàng);3.手動(dòng)認(rèn)證時(shí)將remember參數(shù)傳遞給Auth::attempt()方法以啟用持久登錄;4.“記住我”默認(rèn)持續(xù)5年,可通過(guò)config/auth.php中的remember_for配置項(xiàng)自定義時(shí)長(zhǎng);5.Laravel自動(dòng)在密碼更改或用戶刪除時(shí)使remember_token失效,建議生產(chǎn)環(huán)境使用HTTPS保障安全;6
