2025年12月3日 星期三

Laravel 12 Eloquent 關聯完整指南:從基礎到進階的全方位教學

相關系列文章:
01.在 windows 10 安裝 laravel 12 studentManagement環境與設定
02.laravel 12 route 路由
03.laravel 12 Blade Templates 網頁模版
04.laravel 12 Controller 控制器 
05.Laravel 12 Migration 遷移-資料庫版本控制
06.Laravel 12 Model 資料庫中的資料表,並提供與資料庫互動的介面
07.laravel 資料庫資料填充工廠入門
08.laravel 12 Eloquent ORM-Query Builder
09.laravel 12 Eloquent ORM-Eloquent ORM
10.Laravel 12:Eloquent 必學技巧一次掌握(Scopes、Soft Deletes、CRUD)
11.Laravel 12 表單驗證教學
12.Laravel 12 圖片上傳與刪除記錄及文件
13.Laravel 12 Eloquent 關聯完整指南:從基礎到進階的全方位教學

在這章節,總共分成6大部分:
1.Laravel 12 一對一關聯教學|Eloquent 關聯完整解說
2.Laravel 12 一對多關聯教學|掌握 Eloquent 關聯
3.Laravel 12 多對多關聯教學|Eloquent Pivot 樞紐表詳解
4.Laravel 12 Has One Through 關聯|Eloquent 間接一對一關聯
5.Laravel 12 Has Many Through 關聯|透過 Eloquent 取得間接的相關資料
6.Laravel 12 多型關聯解說|一個模型對應多個資料表
其細節討論如下:

1.Laravel 12 一對一關聯教學|Eloquent 關聯完整解說


2.Laravel 12 一對多關聯教學|掌握 Eloquent 關聯


3.Laravel 12 多對多關聯教學|Eloquent Pivot 樞紐表詳解


4.Laravel 12 Has One Through 關聯|Eloquent 間接一對一關聯


5.Laravel 12 Has Many Through 關聯|透過 Eloquent 取得間接的相關資料


6.Laravel 12 多型關聯解說|一個模型對應多個資料表












資料來源: 
1.Laravel 12 Eloquent Relationships Introduction | One to One, One to Many, Many to Many
2.Laravel 12 One to One Relationship Tutorial | Eloquent Relationship Explained
3.Laravel 12 One to Many Relationship Tutorial | Master Eloquent Relationships
4.Laravel 12 Many to Many Relationship Tutorial | Eloquent Pivot Table Explained







2025年12月2日 星期二

Laravel 12 圖片上傳與刪除記錄及文件

相關系列文章:
01.在 windows 10 安裝 laravel 12 studentManagement環境與設定
02.laravel 12 route 路由
03.laravel 12 Blade Templates 網頁模版
04.laravel 12 Controller 控制器 
05.Laravel 12 Migration 遷移-資料庫版本控制
06.Laravel 12 Model 資料庫中的資料表,並提供與資料庫互動的介面
07.laravel 資料庫資料填充工廠入門
08.laravel 12 Eloquent ORM-Query Builder
09.laravel 12 Eloquent ORM-Eloquent ORM
10.Laravel 12:Eloquent 必學技巧一次掌握(Scopes、Soft Deletes、CRUD)
11.Laravel 12 表單驗證教學
12.Laravel 12 圖片上傳與刪除記錄及文件
13.Laravel 12 Eloquent 關聯完整指南:從基礎到進階的全方位教學

Laravel 12 圖片上傳與刪除記錄及文件,共有兩個主題,分別是
1. 在 Laravel 12 中上傳與儲存圖片
2. 刪除記錄及圖片(從儲存設備中刪除文件)

1. 在 Laravel 12 中上傳與儲存圖片
(1).在資料表裡新增Image的欄位:
指令: php artisan make:migration AddImageToStudentsTable


在\database\migrations\xxxx_xx_xx_xxxxxx_add_image_to_students_table.php,
            $table->string('Image')->nullable(true);
            $table->dropColumn('Image');
如下圖:
指令:php artisan migrate
在/resources/views/students/add.blade.php ,添加
<div class="mb-3">
<label for="Image" class="form-label">Image</label>
 <input type="file" class="form-control" id="Image" name="Image" accept="image/*">
</div>
如下圖:
http://127.0.0.1:8000/student/add,可以看到
在\app\Http\Requests\StudentAddRequest.php 新增
            'Image' => 'nullable|image|mimes:png,jpg,gif|max:2048',    
如下圖:
在\app\Http\Controllers\StudentController.php 新增
        $imagePath = null;
        if ($request->hasFile('Image')) {
            $imagePath = $request->file('Image')->store('photos','public');
        }
        $student->Image = $imagePath;
如下圖:
\resources\views\students\add.blade.php 編輯如下:
enctype="multipart/form-data"
如下圖:
在 127.0.0.1:8000/student/add 填寫資料,並按下Submit
此時,會在/storage/app/public/photos 看到,如下圖:
此時,下指令:php artisan storage:link 
這會讓 public/storage 對應到 storage/app/public
在 127.0.0.1:8080/phpmyadmin,可看到:
在/resources/views/students/index.blade.php ,添加
      <th>Image</th>
  <td>
     @if ($student->Image)
        <img src="{{ asset('storage/' . $student->Image) }}" width="150">
     @endif
  </td>
如下圖:
在 127.0.0.1:8000/student的最盡頭,可以看到縮圖

(2)若要能進行更新圖片
在/resources/views/students/edit.blade.php ,添加

enctype="multipart/form-data"

 <div class="mb-3">
   @if ($student->Image)
      <img src="{{ asset('storage/' . $student->Image) }}" width="150">
   @endif
  <label for="image" class="form-label">Image</label>
  <input type="file" class="form-control" id="Image" name="Image" accept="Image/*">
 </div>

如下圖:

在\app\Http\Controllers\StudentController.php 新增

        $imagePath = null;
        if ($request->hasFile('Image')) {
            $imagePath = $request->file('Image')->store('photos', 'public');
        }

$student->Image = $imagePath;

如下圖:

http://127.0.0.1:8000/student/add,可以看到,按下Update
可以看到,可以編修時,更新照片


2. 刪除記錄及圖片(從儲存設備中刪除文件)
注意事項:

use Illuminate\Support\Facades\Storage;

在\app\Http\Controllers\StudentController.php 變更編輯如下:

        $student = Student::findOrFail($id);
        if ($student->Image) {
            Storage::disk('public')->delete($student->Image);
        }
        $student->delete();
               
        return redirect('student');

如下圖:

在 127.0.0.1:8000/student的最盡頭,可以看到縮圖。按下Delete
就可以看到,在/public/storage/photos/ 的照片少一張

資料來源:
1.Laravel 12 Image Upload Tutorial | How to Upload & Store Images in Laravel
2.Laravel 12 – Delete Record with Image | Remove File from Storage


2025年11月30日 星期日

Laravel 12 表單驗證教學

相關系列文章:
01.在 windows 10 安裝 laravel 12 studentManagement環境與設定
02.laravel 12 route 路由
03.laravel 12 Blade Templates 網頁模版
04.laravel 12 Controller 控制器 
05.Laravel 12 Migration 遷移-資料庫版本控制
06.Laravel 12 Model 資料庫中的資料表,並提供與資料庫互動的介面
07.laravel 資料庫資料填充工廠入門
08.laravel 12 Eloquent ORM-Query Builder
09.laravel 12 Eloquent ORM-Eloquent ORM
10.Laravel 12:Eloquent 必學技巧一次掌握(Scopes、Soft Deletes、CRUD)
11.Laravel 12 表單驗證教學
12.Laravel 12 圖片上傳與刪除記錄及文件
13.Laravel 12 Eloquent 關聯完整指南:從基礎到進階的全方位教學

Laravel 12 表單驗證教學包含兩個子項目,分別是
1.Laravel 12 表單驗證教學|用正確方式驗證使用者輸入
2.Laravel 12 的 Form Request 驗證|乾淨且組織化的驗證方式

以下為各分項的詳細內容:

1.Laravel 12 表單驗證教學|用正確方式驗證使用者輸入
在\resources\views\students\add.blade.php 去除 required
@extends('layouts.app')
@section('head')
    <title>Add Students</title>
@endsection

@section('content')
    <section>
        <div class="card shadow-lg">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0">Student Registration</h5>
            </div>
            <div class="card-body">
                <form action="{{ URL('student/create') }}" method="POST">
                    @csrf
                    <div class="mb-3">
                        <label for="name" class="form-label">Name</label>
                        <input type="text" class="form-control" id="name" name="name">
                    </div>
                    <div class="mb-3">
                        <label for="email" class="form-label">Email</label>
                        <input type="email" class="form-control" id="email" name="email">
                    </div>
                    <div class="mb-3">
                        <label for="age" class="form-label">Age</label>
                        <input type="number" class="form-control" id="age" name="age">
                    </div>
                    <div class="mb-3">
                        <label for="age" class="form-label">Date of Birth</label>
                        <input type="date" class="form-control" id="date_of_birth" name="date_of_birth">
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Gender</label>
                        <div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="gender" id="male" value="m" >
                                <label class="form-check-label" for="male">Male</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" type="radio" name="gender" id="female" value="f">
                                <label class="form-check-label" for="female">Female</label>
                            </div>
                        </div>
                    </div>
                    <button type="submit" class="btn btn-success">送出</button>
                </form>
            </div>
        </div>
    </section>
@endsection

在http://127.0.0.1:8000/student/add,什麼資料都不填,直接按下[送出]
就會看到
我們需要在後端作驗證:
在\app\Http\Controllers\StudentController.php 編輯
        $request->validate([
            'name'  => 'required|string|max:255',
            'email' => 'required|email|unique:students,email',
            'age'   => 'required|integer|min:1|max:100',
            'date_of_birth' => 'required|date',
            'gender' => 'required|in:m,f',    
        ]);
如下圖:

為了能夠顯示錯誤訊息,所以我們在\resources\views\students\add.blade.php 編輯如下:
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

如下圖:
在http://127.0.0.1:8000/student/add,什麼資料都不填,直接按下[送出]
亦可以自訂錯誤訊息。
在\app\Http\Controllers\StudentController.php 編輯
        $request->validate([
            'name'  => 'required|string|max:255',
            'email' => 'required|email|unique:students,email',
            'age'   => 'required|integer|min:1|max:100',
            'date_of_birth' => 'required|date',
            'gender' => 'required|in:m,f',
        ],[
           'name.required'  => 'Please Write Student Name',
           'age.max' => 'Student can not be older than 100.',
        ]);
如下圖所示:
在http://127.0.0.1:8000/student/add,年紀改填,直接按下[送出]
就可以看到

2.Laravel 12 的 Form Request 驗證|乾淨且組織化的驗證方式
如果將驗證通通寫在Controller ,則Controller 將會異常肥大,管理起來也不方便。因此,將驗證功能移到另一個功能request。

指令:php artisan make:request StudentAddRequest

則會在app\Http\Request\新增一個StudentAddRequest.php
如何讓app\Http\Request\StudentAddRequest.php 可以執行?
    public function authorize(): bool
    {
        return true;
    }

如下圖:
在\app\Http\Controllers\StudentController.php 的設定,重新調整寫入至\app\Http\Request\StudentAddRequest.php
    public function rules(): array
    {
        return [
            //
            'name'  => 'required|string|max:255',
            'email' => 'required|email|unique:students,email',
            'age'   => 'required|integer|min:1|max:100',
            'date_of_birth' => 'required|date',
            'gender' => 'required|in:m,f',
        ];
    }

    public function messages()
    {
        return [
           'name.required'  => 'Please Write Student Name',
           'age.max' => 'Student can not be older than 100.',
        ];
    }

如下圖:
那要如何加入
\app\Http\Controllers\StudentController.php
原先的
  public function create(Request $request) {
要改為
    public function create(StudentAddRequest $request) {
如下圖:
在http://127.0.0.1:8000/student/add,年紀改填,直接按下[送出]
就可以看到
此時,原先的錯誤資料都會被清空。那我要如何保留原先的資料,進行修改?
\resources\views\students\add.blade.php 編輯如下:
value="{{ old('name') }}"
value="{{ old('email') }}"
value="{{ old('age') }}"
value={{ old('date_of_birth') }}
value="m" {{ old('gender')== 'm' ? 'checked':'' }}
value="f" {{ old('gender')== 'f' ? 'checked':'' }}

如下圖:

在http://127.0.0.1:8000/student/add,填入資料,只有age為200,按下submit。就會得到
就會看到,舊的值都會被保留下來
                                          


資料來源:
1.Laravel 12 Form Validation Tutorial | Validate User Input the Right Way
2.Laravel 12 Form Request Validation | Clean & Organized Validation in Laravel
3.11 adding old value


Laravel 12 Eloquent 關聯完整指南:從基礎到進階的全方位教學

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