2025年11月20日 星期四

Laravel 12:Eloquent 必學技巧一次掌握(Scopes、Soft Deletes、CRUD)


涵蓋主題如下:
一、Query Scopes:打造更乾淨且可重複使用的查詢邏輯
二、Soft Deletes:進行軟刪除並可還原資料
三、CRUD(Read):用 Eloquent 讀取資料
四、Table Filters:動態搜尋與條件篩選
五、Pagination:最佳化資料瀏覽與分頁
六、CRUD(Create):建立資料
七、CRUD(Update):更新資料
八、CRUD(Delete):刪除資料

一、Query Scopes:打造更乾淨且可重複使用的查詢邏輯
        觀念:Query Scope(查詢作用域) 是 Laravel Eloquent 提供的一種功能,用來把常用的查詢條件封裝起來,讓你的查詢程式碼更乾淨、可重複使用、可讀性更高。簡單說:把常用的 where、orderBy… 等查詢邏輯集中管理,並用簡短語法呼叫。

1.建立Query Scope(查詢作用域)---一個參數
在models\Student.php
輸入如下:
  public function scopeMale($query) {
    return $query->where('gender','m');
  }
如下圖:
在Http\Controller\StudentController.php
輸入如下:
    public function queryScope() {
        $item = Student::male()->get();
        return $item;
    }
    public function secondQuery() {
        $item = Student::male()->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('query-scope',[StudentController::class,'queryScope']);
Route::get('second-query',[StudentController::class,'secondQuery']);
如下圖
接下來,下指令 php artisan serve
在網址輸入:  http://127.0.0.1:8000/query-scope
                          http://127.0.0.1:8000/second-query
就會出現 
接下來,修改Query Scope(查詢作用域)
在models\Student.php
輸入如下:
  public function scopeMale($query) {
    return $query->where('gender','m')->where('age','18');
  }
如下圖:
接下來,其餘不變。下指令 php artisan serve
在網址輸入:  http://127.0.0.1:8000/query-scope
                          http://127.0.0.1:8000/second-query
就會出現

2.建立Query Scope(查詢作用域)---一個參數
在models\Student.php
輸入如下:
  public function scopeFemale($query) {
    return $query->where('gender','f')->where('age','18');
  }
如下圖:
在Http\Controller\StudentController.php
輸入如下:
    public function thirdScope() {
        $item = Student::female()->get();
        return $item;
    }
    public function fourQuery() {
        $item = Student::female()->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('third-scope',[StudentController::class,'thirdScope']);
Route::get('four-query',[StudentController::class,'fourQuery']);
如下圖
接下來,下指令 php artisan serve
在網址輸入:  http://127.0.0.1:8000/third-scope
                          http://127.0.0.1:8000/four-query
就會出現 

3.建立Query Scope(查詢作用域)---二個參數
在models\Student.php
輸入如下:
  public function scopeMale($query,$age=18) {
    return $query->where('gender','m')->where('age',$age);
  }
  public function scopeFemale($query,$age=18) {
    return $query->where('gender','f')->where('age',$age);
  }
如下圖:
在Http\Controller\StudentController.php
輸入如下:
    public function queryScope() {
        $item = Student::male(25)->get();
        return $item;
    }
    public function thirdScope() {
        $item = Student::female(25)->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('query-scope',[StudentController::class,'queryScope']);
Route::get('third-scope',[StudentController::class,'thirdScope']);
如下圖
接下來,下指令 php artisan serve
在網址輸入:  http://127.0.0.1:8000/query-scope
                          http://127.0.0.1:8000/third-query
就會出現 


二、Soft Deletes:進行軟刪除並可還原資料
      觀念:Laravel 12(以及早期版本)中,Soft Deletes(軟刪除)是 Eloquent ORM 提供的一種資料刪除方式,讓你的「刪除」操作不會真的把資料從資料庫移除,而是將資料標記為已刪除,以便未來可恢復、查詢紀錄或避免資料遺失。

1.在學生表建立一個新列,然後清除所有資料。
指令:php artisan make:migration addSoftDeleteToStudentsTable
接下來,在database\migrations\2025_11_21_190645_add_soft_delete_to_students_table.php 
加上這句
            $table->softDeletes();
如下圖:
然後輸入指令:php artisan migrate
進入網址:http://127.0.0.1:8080/phpmyadmin/index.php
可看到





三、CRUD(Read):用 Eloquent 讀取資料

四、Table Filters:動態搜尋與條件篩選

五、Pagination:最佳化資料瀏覽與分頁

六、CRUD(Create):建立資料

七、CRUD(Update):更新資料

八、CRUD(Delete):刪除資料







資料來源:

2025年11月16日 星期日

laravel 12 Eloquent ORM-Eloquent ORM

1.插入第一筆資料的名字
在Http\Controller\StudentController.php
輸入如下:
    public function addData(){
        $item = new Student();
        $item->name = 'tester';
        $item->email = 'tester@gmail.com';
        $item->age = 25;
        $item->date_of_birth = '2010-01-01';
        $item->gender = 'f';
        $item->save();
        return 'Added Successfully!';
    }
如下圖:
在\routes\web.php 加入
Route::get('add-data',[StudentController::class,'addData']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/add-data
就會出現 
在網址輸入:
http://127.0.0.1:8080/phpmyadmin/index.php?route=/sql&db=studentmanagement&table=students&pos=0
就會出現 

二、利用Eloquent ORM 在資料庫(DataBase) 取得(Fetch)資料(Data):
1.取得所有資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMgetData(){
        $item = Student::all();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-get-data',[StudentController::class,'ORMgetData']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-get-data
就會出現 
2.取得所有資料的部分欄位(id 與 name)
在Http\Controller\StudentController.php
輸入如下:
    public function ORMgetDataSelect(){
        $item = Student::select('id','name')->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-get-data-select',[StudentController::class,'ORMgetDataSelect']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-get-data-select
就會出現 
3.取得指定資料的部分欄位(id 與 name)
在Http\Controller\StudentController.php
輸入如下:
    public function ORMgetDataWhere() {
        $item = Student::select('id','name')->where('id',20)->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-get-data-where',[StudentController::class,'ORMgetDataWhere']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-get-data-where
就會出現 

4.另一種取得指定資料的部分欄位(id 與 name)
在Http\Controller\StudentController.php
輸入如下:
    public function ORMgetDataFind() {
        $item = Student::select('id','name')->find(20);
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-get-data-find',[StudentController::class,'ORMgetDataFind']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-get-data-find
就會出現 

5.若要隱藏指定資料的部分欄位(name)
在app\Models\Student.php
輸入如下:
    protected $hidden = [
        'name',
    ];
在Http\Controller\StudentController.php
輸入如下:
    public function ORMgetDataFind() {
        $item = Student::select('id','name')->find(20);
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-get-data-find',[StudentController::class,'ORMgetDataFind']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-get-data-find
就會出現 

三、利用Eloquent ORM 在資料庫(DataBase) 更新(Update)資料(Data):
1.更新一筆資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMupdateData(){
        $item = Student::find(20);
        $item->name = 'Updated Name';
        $item->age = 10;
        $item->update();
        return 'Updated Succeddfully!';
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-update-data',[StudentController::class,'ORMupdateData']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-update-data
就會出現 
在網址輸入: http://127.0.0.1:8000/orm-get-data-find
就會出現 

四、利用Eloquent ORM 在資料庫(DataBase) 刪除(Delete)資料(Data):
1.刪除一筆資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMdeleteData(){
        $item = Student::find(20);
        $item->delete();
        return 'Deleted Successfully';
    }

如下圖:
在\routes\web.php 加入
Route::get('orm-update-data',[StudentController::class,'ORMupdateData']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-delete-data
就會出現 
在網址輸入: http://127.0.0.1:8000/orm-get-data
就會出現 

2.若已刪除一筆資料,則會出現404
在Http\Controller\StudentController.php
輸入如下:
    public function ORMdeleteData(){
        $item = Student::findorFail(20);
        $item->delete();
        return 'Deleted Successfully';
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-update-data',[StudentController::class,'ORMupdateData']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-delete-data
就會出現 

五、利用Eloquent ORM 在資料庫(DataBase) 使用 where 條件:
1.取得 18歲以上 的資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMwhereConditions(){
        $item=Student::Where('age','>',17)->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-where-conditions',[StudentController::class,'ORMwhereConditions']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-where-conditions
就會出現 

2.取得 18歲以上 與 女性 的資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMwhereConditions(){
        $item=Student::Where('age','>',17)
        ->Where('gender','f')
        ->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-where-conditions',[StudentController::class,'ORMwhereConditions']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-where-conditions
就會出現 

3.取得 18歲以上 或 男性 的資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMwhereConditions(){
        $item=Student::Where('age','>',17)
        ->orWhere('gender','f')
        ->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-where-conditions',[StudentController::class,'ORMwhereConditions']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-where-conditions
就會出現 

4.取得 女性 且 小於15歲 或 大於20歲 的資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMwhereConditions() {
        $item = Student::where('gender', 'f')
            ->where(function ($query) {
                $query->where('age', '<', 15)
                    ->orWhere('age', '>', 20);
            })->get();
        return $item;
    }   
如下圖:
在\routes\web.php 加入
Route::get('orm-where-conditions', [StudentController::class, 'ORMwhereConditions']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-where-conditions
就會出現 

5.取得 大於50歲 或 小於60歲 的資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMwhereBetween() {
        $item = Student::whereBetween('age', [50, 60])->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-where-between', [StudentController::class, 'ORMwhereBetween']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-where-between
就會出現 

6.取得  小於10歲 或 大於30歲 的資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMwhereNotBetween() {
        $item = Student::whereNotBetween('age', [10, 30])->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-where-between', [StudentController::class, 'ORMwhereBetween']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-where-between
就會出現 

7.取得  欄位id的 1~5 筆資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMwhereIn() {
        $item = Student::whereIn('id', [1,2,3,4,5])->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-where-in', [StudentController::class, 'ORMwhereIn']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-where-in
就會出現 

8.取得  欄位id的 1~5 筆以外的資料
在Http\Controller\StudentController.php
輸入如下:
    public function ORMwhereNotIn() {
        $item = Student::whereNotIn('id', [1,2,3,4,5])->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-where-not-in', [StudentController::class, 'ORMwhereNotIn']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-where-not-in
就會出現 

9.取得  欄位id 為25 且 欄位age 為 25 
在Http\Controller\StudentController.php
輸入如下:
    public function ORMwhereAll() {
        $item = Student::whereAll(['id','age'],"=", 25)->get();
        return $item;
    }
如下圖:
在\routes\web.php 加入
Route::get('orm-where-all', [StudentController::class, 'ORMwhereAll']);
如下圖
接下來,下指令 php artisan serve
在網址輸入: http://127.0.0.1:8000/orm-where-all
就會出現 

資料來源:

Laravel 12:Eloquent 必學技巧一次掌握(Scopes、Soft Deletes、CRUD)

相關系列文章: 01. 在 windows 10 安裝 laravel 12 studentManagement環境與設定 02. laravel 12 route 路由 03. laravel 12 Blade Templates 網頁模版 04. laravel 12 Con...