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 圖片上傳與刪除記錄及文件

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')) {
            $photoPath = $request->file('image')->store('photos','public');
        }
        $student->image = $imagePath;
如下圖:
\resources\views\students\add.blade.php 編輯如下:

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

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