Xem xét mối quan hệ giữa table cusc_sanpham và cusc_hinhanh
Laravel_SunShine_LoaiSanPham_Sanpham_HinhAnh
Thiết kế của table cusc_hinhanh
cusc_hinhanh sử dụng cặp khóa chính gồm 2 cột (columns) là sp_ma và ha_stt nên chúng ta cần hiệu chỉnh model HinhAnh để có thể đáp ứng được việc lưu trữ cặp khóa chính thông qua Laravel như sau:
Step 1: Hiệu chỉnh file model app\HinhAnh.php, bổ sung các hàm xử lý với trường hợp sử dụng cặp khóa chính (Multi PrimaryKey) model HinhAnh:
php
1<?php2 3namespace App;4 5use Illuminate\Database\Eloquent\Builder;6use Illuminate\Database\Eloquent\Model;7 8class HinhAnh extends Model9{10 public $timestamps = false; //created_at, updated_at11 12 protected $table = 'cusc_hinhanh';13 protected $fillable = ['ha_ten'];14 protected $guarded = ['sp_ma', 'ha_stt'];15 16 protected $primaryKey = ['sp_ma', 'ha_stt'];17 public $incrementing = false;18 19 /**20 * Set the keys for a save update query.21 *22 * @param \Illuminate\Database\Eloquent\Builder $query23 * @return \Illuminate\Database\Eloquent\Builder24 */25 protected function setKeysForSaveQuery(Builder $query)26 {27 $keys = $this->getKeyName();28 if(!is_array($keys)){29 return parent::setKeysForSaveQuery($query);30 }31 32 foreach($keys as $keyName){33 $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));34 }35 36 return $query;37 }38 39 /**40 * Get the primary key value for a save query.41 *42 * @param mixed $keyName43 * @return mixed44 */45 protected function getKeyForSaveQuery($keyName = null)46 {47 if(is_null($keyName)){48 $keyName = $this->getKeyName();49 }50 51 if (isset($this->original[$keyName])) {52 return $this->original[$keyName];53 }54 55 return $this->getAttribute($keyName);56 }57}Step 2: Thêm các hàm lấy danh sách Hình ảnh liên quan trong Model:
php
1<?php2 3namespace App;4 5use Illuminate\Database\Eloquent\Model;6use Carbon\Carbon;7 8class SanPham extends Model9{10 const CREATED_AT = 'sp_taoMoi';11 const UPDATED_AT = 'sp_capNhat';12 13 protected $table = 'cusc_sanpham';14 protected $fillable = ['sp_ten', 'sp_giaGoc', 'sp_giaBan', 'sp_hinh', 'sp_thongTin', 'sp_danhGia', 'sp_taoMoi', 'sp_capNhat', 'sp_trangThai', 'l_ma'];15 protected $guarded = ['sp_ma'];16 17 protected $primaryKey = 'sp_ma';18 19 protected $dates = ['sp_taoMoi', 'sp_capNhat'];20 protected $dateFormat = 'Y-m-d H:i:s';21 22 public function loaisanpham()23 {24 return $this->belongsTo('App\Loai', 'l_ma', 'l_ma');25 }26 27 public function hinhanhlienquan()28 {29 return $this->hasMany('App\HinhAnh', 'sp_ma', 'sp_ma');30 }31}Step 3: Hiệu chỉnh chức năng Thêm mới Sản phẩm (create), bổ sung thêm ô chọn file cho phép người dùng upload cùng lúc nhiều hình ảnh
- Hiệu chỉnh view:
resources/views/backend/sanpham/create.blade.php
php
1@extends('backend.layouts.master')2 3@section('title')4Thêm mới sản phẩm5@endsection6 7@section('custom-css')8<!-- Các css dành cho thư viện bootstrap-fileinput -->9<link href="{{ asset('vendor/bootstrap-fileinput/css/fileinput.css') }}" media="all" rel="stylesheet" type="text/css" />10<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" crossorigin="anonymous">11<link href="{{ asset('vendor/bootstrap-fileinput/themes/explorer-fas/theme.css') }}" media="all" rel="stylesheet" type="text/css" />12@endsection13 14@section('content')15@if ($errors->any())16<div class="alert alert-danger">17 <ul>18 @foreach ($errors->all() as $error)19 <li>{{ $error }}</li>20 @endforeach21 </ul>22</div>23@endif24 25<form method="post" action="{{ route('admin.sanpham.store') }}" enctype="multipart/form-data">26 {{ csrf_field() }}27 <div class="form-group">28 <label for="l_ma">Loại sản phẩm</label>29 <select name="l_ma" class="form-control">30 @foreach($danhsachloai as $loai)31 @if(old('l_ma') == $loai->l_ma)32 <option value="{{ $loai->l_ma }}" selected>{{ $loai->l_ten }}</option>33 @else34 <option value="{{ $loai->l_ma }}">{{ $loai->l_ten }}</option>35 @endif36 @endforeach37 </select>38 </div>39 <div class="form-group">40 <label for="sp_ten">Tên sản phẩm</label>41 <input type="text" class="form-control" id="sp_ten" name="sp_ten" value="{{ old('sp_ten') }}">42 </div>43 <div class="form-group">44 <label for="sp_giaGoc">Giá gốc</label>45 <input type="text" class="form-control" id="sp_giaGoc" name="sp_giaGoc" value="{{ old('sp_giaGoc') }}">46 </div>47 <div class="form-group">48 <label for="sp_giaGoc">Giá bán</label>49 <input type="text" class="form-control" id="sp_giaBan" name="sp_giaBan" value="{{ old('sp_giaBan') }}">50 </div>51 <div class="form-group">52 <div class="file-loading">53 <label>Hình đại diện</label>54 <input id="sp_hinh" type="file" name="sp_hinh">55 </div>56 </div>57 <div class="form-group">58 <label for="sp_thongTin">Thông tin</label>59 <input type="text" class="form-control" id="sp_thongTin" name="sp_thongTin" value="{{ old('sp_thongTin') }}">60 </div>61 <div class="form-group">62 <label for="sp_danhGia">Đánh giá</label>63 <input type="text" class="form-control" id="sp_danhGia" name="sp_danhGia" value="{{ old('sp_danhGia') }}">64 </div>65 <div class="form-group">66 <label for="sp_taoMoi">Ngày tạo mới</label>67 <input type="text" class="form-control" id="sp_taoMoi" name="sp_taoMoi" value="{{ old('sp_taoMoi') }}">68 </div>69 <div class="form-group">70 <label for="sp_capNhat">Ngày cập nhật</label>71 <input type="text" class="form-control" id="sp_capNhat" name="sp_capNhat" value="{{ old('sp_capNhat') }}">72 </div>73 <div class="form-group">74 <label for="sp_trangThai">Trạng thái</label>75 <select name="sp_trangThai" class="form-control">76 <option value="1" {{ old('sp_trangThai') == 1 ? "selected" : "" }}>Khóa</option>77 <option value="2" {{ old('sp_trangThai') == 2 ? "selected" : "" }}>Khả dụng</option>78 </select>79 </div>80 <div class="form-group">81 <div class="file-loading">82 <label>Hình ảnh liên quan sản phẩm</label>83 <input id="sp_hinhanhlienquan" type="file" name="sp_hinhanhlienquan[]" multiple>84 </div>85 </div>86 <button type="submit" class="btn btn-primary">Lưu</button>87</form>88@endsection89 90@section('custom-scripts')91<!-- Các script dành cho thư viện bootstrap-fileinput -->92<script src="{{ asset('vendor/bootstrap-fileinput/js/plugins/sortable.js') }}" type="text/javascript"></script>93<script src="{{ asset('vendor/bootstrap-fileinput/js/fileinput.js') }}" type="text/javascript"></script>94<script src="{{ asset('vendor/bootstrap-fileinput/js/locales/fr.js') }}" type="text/javascript"></script>95<script src="{{ asset('vendor/bootstrap-fileinput/themes/fas/theme.js') }}" type="text/javascript"></script>96<script src="{{ asset('vendor/bootstrap-fileinput/themes/explorer-fas/theme.js') }}" type="text/javascript"></script>97 98<script>99 $(document).ready(function() {100 $("#sp_hinh").fileinput({101 theme: 'fas',102 showUpload: false,103 showCaption: false,104 browseClass: "btn btn-primary btn-lg",105 fileType: "any",106 previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",107 overwriteInitial: false108 });109 110 // Ô nhập liệu cho phép chọn nhiều hình ảnh cùng lúc (các hình ảnh liên quan đến sản phẩm)111 $("#sp_hinhanhlienquan").fileinput({112 theme: 'fas',113 showUpload: false,114 showCaption: false,115 browseClass: "btn btn-primary btn-lg",116 fileType: "any",117 previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",118 overwriteInitial: false,119 allowedFileExtensions: ["jpg", "gif", "png", "txt"]120 });121 });122</script>123 124<!-- Các script dành cho thư viện Mặt nạ nhập liệu InputMask -->125<script src="{{ asset('vendor/input-mask/jquery.inputmask.min.js') }}"></script>126<script src="{{ asset('vendor/input-mask/bindings/inputmask.binding.js') }}"></script>127 128<script>129 $(document).ready(function() {130 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Giá gốc131 $('#sp_giaGoc').inputmask({132 alias: 'currency',133 positionCaretOnClick: "radixFocus",134 radixPoint: ".",135 _radixDance: true,136 numericInput: true,137 groupSeparator: ",",138 suffix: ' vnđ',139 min: 0, // 0 ngàn140 max: 100000000, // 1 trăm triệu141 autoUnmask: true,142 removeMaskOnSubmit: true,143 unmaskAsNumber: true,144 inputtype: 'text',145 placeholder: "0",146 definitions: {147 "0": {148 validator: "[0-9\uFF11-\uFF19]"149 }150 }151 });152 153 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Giá bán154 $('#sp_giaBan').inputmask({155 alias: 'currency',156 positionCaretOnClick: "radixFocus",157 radixPoint: ".",158 _radixDance: true,159 numericInput: true,160 groupSeparator: ",",161 suffix: ' vnđ',162 min: 0, // 0 ngàn163 max: 100000000, // 1 trăm triệu164 autoUnmask: true,165 removeMaskOnSubmit: true,166 unmaskAsNumber: true,167 inputtype: 'text',168 placeholder: "0",169 definitions: {170 "0": {171 validator: "[0-9\uFF11-\uFF19]"172 }173 }174 });175 176 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Ngày tạo mới177 $('#sp_taoMoi').inputmask({178 alias: 'datetime',179 inputFormat: 'yyyy-mm-dd' // Định dạng Năm-Tháng-Ngày180 });181 182 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Ngày cập nhật183 $('#sp_capNhat').inputmask({184 alias: 'datetime',185 inputFormat: 'yyyy-mm-dd' // Định dạng Năm-Tháng-Ngày186 });187 });188</script>189 190@endsectionStep 4: hiệu chỉnh action store của Backend\SanPhamController
Bổ sung chức năng Lưu trữ cùng lúc nhiều hình ảnh
php
1use App\HinhAnh; // Chúng ta cần sử dụng model HinhAnh để truy vấn dữ liệu2 3/**4 * Store a newly created resource in storage.5 *6 * @param \Illuminate\Http\Request $request7 * @return \Illuminate\Http\Response8 */9public function store(Request $request)10{11 // Bổ sung ràng buộc Validate12 $validation = $request->validate([13 'sp_hinh' => 'required|file|image|mimes:jpeg,png,gif,webp|max:2048',14 15 // Cú pháp dùng upload nhiều file16 'sp_hinhanhlienquan.*' => 'file|image|mimes:jpeg,png,gif,webp|max:2048'17 ]);18 19 // Tạo mới object SanPham20 $sp = new SanPham();21 $sp->sp_ten = $request->sp_ten;22 $sp->sp_giaGoc = $request->sp_giaGoc;23 $sp->sp_giaBan = $request->sp_giaBan;24 $sp->sp_thongTin = $request->sp_thongTin;25 $sp->sp_danhGia = $request->sp_danhGia;26 $sp->sp_taoMoi = $request->sp_taoMoi;27 $sp->sp_capNhat = $request->sp_capNhat;28 $sp->sp_trangThai = $request->sp_trangThai;29 $sp->l_ma = $request->l_ma;30 31 // Kiểm tra xem người dùng có upload hình ảnh Đại diện hay không?32 if ($request->hasFile('sp_hinh')) {33 $file = $request->sp_hinh;34 35 // Lưu tên hình vào column sp_hinh36 $sp->sp_hinh = $file->getClientOriginalName();37 38 // Chép file vào thư mục "storate/public/photos"39 $fileSaved = $file->storeAs('public/photos', $sp->sp_hinh);40 }41 $sp->save();42 43 // Lưu hình ảnh liên quan44 if($request->hasFile('sp_hinhanhlienquan')) {45 $files = $request->sp_hinhanhlienquan;46 47 // duyệt từng ảnh và thực hiện lưu48 foreach ($request->sp_hinhanhlienquan as $index => $file) {49 50 $file->storeAs('public/photos', $file->getClientOriginalName());51 52 // Tạo đối tưọng HinhAnh53 $hinhAnh = new HinhAnh();54 $hinhAnh->sp_ma = $sp->sp_ma;55 $hinhAnh->ha_stt = ($index + 1);56 $hinhAnh->ha_ten = $file->getClientOriginalName();57 $hinhAnh->save();58 }59 }60 61 // Hiển thị câu thông báo 1 lần (Flash session)62 Session::flash('alert-info', 'Them moi thanh cong ^^~!!!');63 64 // Điều hướng về route index65 return redirect()->route('admin.sanpham.index');66}Step 5: Hiệu chỉnh chức năng Sửa Sản phẩm (edit), bổ sung thêm ô chọn file cho phép người dùng upload cùng lúc nhiều hình ảnh
- Hiệu chỉnh view:
resources/views/backend/sanpham/edit.blade.php
php
1@extends('backend.layouts.master')2 3@section('title')4Hiệu chỉnh sản phẩm5@endsection6 7@section('custom-css')8<!-- Các css dành cho thư viện bootstrap-fileinput -->9<link href="{{ asset('vendor/bootstrap-fileinput/css/fileinput.css') }}" media="all" rel="stylesheet" type="text/css"/>10<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.5.0/css/all.css" crossorigin="anonymous">11<link href="{{ asset('vendor/bootstrap-fileinput/themes/explorer-fas/theme.css') }}" media="all" rel="stylesheet" type="text/css"/>12@endsection13 14@section('content')15@if ($errors->any())16 <div class="alert alert-danger">17 <ul>18 @foreach ($errors->all() as $error)19 <li>{{ $error }}</li>20 @endforeach21 </ul>22 </div>23@endif24 25<form method="post" action="{{ route('admin.sanpham.update', ['id' => $sp->sp_ma]) }}" enctype="multipart/form-data">26 <input type="hidden" name="_method" value="PUT" />27 {{ csrf_field() }}28 <div class="form-group">29 <label for="l_ma">Loại sản phẩm</label>30 <select name="l_ma" class="form-control">31 @foreach($danhsachloai as $loai)32 @if($loai->l_ma == $sp->l_ma)33 <option value="{{ $loai->l_ma }}" selected>{{ $loai->l_ten }}</option>34 @else35 <option value="{{ $loai->l_ma }}">{{ $loai->l_ten }}</option>36 @endif37 @endforeach38 </select>39 </div>40 <div class="form-group">41 <label for="sp_ten">Tên sản phẩm</label>42 <input type="text" class="form-control" id="sp_ten" name="sp_ten" value="{{ old('sp_ten', $sp->sp_ten) }}">43 </div>44 <div class="form-group">45 <label for="sp_giaGoc">Giá gốc</label>46 <input type="text" class="form-control" id="sp_giaGoc" name="sp_giaGoc" value="{{ old('sp_giaGoc', $sp->sp_giaGoc) }}">47 </div>48 <div class="form-group">49 <label for="sp_giaGoc">Giá bán</label>50 <input type="text" class="form-control" id="sp_giaBan" name="sp_giaBan" value="{{ old('sp_giaBan', $sp->sp_giaBan) }}">51 </div>52 <div class="form-group">53 <div class="file-loading">54 <label>Hình đại diện</label>55 <input id="sp_hinh" type="file" name="sp_hinh">56 </div>57 </div>58 <div class="form-group">59 <label for="sp_thongTin">Thông tin</label>60 <input type="text" class="form-control" id="sp_thongTin" name="sp_thongTin" value="{{ old('sp_thongTin', $sp->sp_thongTin) }}">61 </div>62 <div class="form-group">63 <label for="sp_danhGia">Đánh giá</label>64 <input type="text" class="form-control" id="sp_danhGia" name="sp_danhGia" value="{{ old('sp_danhGia', $sp->sp_danhGia) }}">65 </div>66 <div class="form-group">67 <label for="sp_taoMoi">Ngày tạo mới</label>68 <input type="text" class="form-control" id="sp_taoMoi" name="sp_taoMoi" value="{{ old('sp_taoMoi', $sp->sp_taoMoi) }}" data-mask-datetime>69 </div>70 <div class="form-group">71 <label for="sp_capNhat">Ngày cập nhật</label>72 <input type="text" class="form-control" id="sp_capNhat" name="sp_capNhat" value="{{ old('sp_capNhat', $sp->sp_capNhat) }}" data-mask-datetime>73 </div>74 <div class="form-group">75 <label for="sp_trangThai">Trạng thái</label>76 <select name="sp_trangThai" class="form-control">77 <option value="1" {{ old('sp_trangThai', $sp->sp_trangThai) == 1 ? "selected" : "" }}>Khóa</option>78 <option value="2" {{ old('sp_trangThai', $sp->sp_trangThai) == 2 ? "selected" : "" }}>Khả dụng</option>79 </select>80 </div>81 <div class="form-group">82 <div class="file-loading">83 <label>Hình ảnh liên quan sản phẩm</label>84 <input id="sp_hinhanhlienquan" type="file" name="sp_hinhanhlienquan[]" multiple>85 </div>86 </div>87 <button type="submit" class="btn btn-primary">Lưu</button>88</form>89@endsection90 91@section('custom-scripts')92<!-- Các script dành cho thư viện bootstrap-fileinput -->93<script src="{{ asset('vendor/bootstrap-fileinput/js/plugins/sortable.js') }}" type="text/javascript"></script>94<script src="{{ asset('vendor/bootstrap-fileinput/js/fileinput.js') }}" type="text/javascript"></script>95<script src="{{ asset('vendor/bootstrap-fileinput/js/locales/fr.js') }}" type="text/javascript"></script>96<script src="{{ asset('vendor/bootstrap-fileinput/themes/fas/theme.js') }}" type="text/javascript"></script>97<script src="{{ asset('vendor/bootstrap-fileinput/themes/explorer-fas/theme.js') }}" type="text/javascript"></script>98 99<script>100 $(document).ready(function() {101 $("#sp_hinh").fileinput({102 theme: 'fas',103 showUpload: false,104 showCaption: false,105 browseClass: "btn btn-primary btn-lg",106 fileType: "any",107 append: false,108 showRemove: false,109 autoReplace: true,110 previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",111 overwriteInitial: false,112 initialPreviewShowDelete: false,113 initialPreviewAsData: true,114 initialPreview: [115 "{{ asset('storage/photos/' . $sp->sp_hinh) }}"116 ],117 initialPreviewConfig: [118 {119 caption: "{{ $sp->sp_hinh }}", 120 size: {{ Storage::exists('public/photos/' . $sp->sp_hinh) ? Storage::size('public/photos/' . $sp->sp_hinh) : 0 }}, 121 width: "120px", 122 url: "{$url}", 123 key: 1124 },125 ]126 });127 128 // Ô nhập liệu cho phép chọn nhiều hình ảnh cùng lúc (các hình ảnh liên quan đến sản phẩm)129 $("#sp_hinhanhlienquan").fileinput({130 theme: 'fas',131 showUpload: false,132 showCaption: false,133 browseClass: "btn btn-primary btn-lg",134 fileType: "any",135 append: false,136 showRemove: false,137 autoReplace: true,138 previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",139 overwriteInitial: false,140 allowedFileExtensions: ["jpg", "gif", "png", "txt"],141 initialPreviewShowDelete: false,142 initialPreviewAsData: true,143 initialPreview: [144 @foreach($sp->hinhanhlienquan()->get() as $hinhAnh)145 "{{ asset('storage/photos/' . $hinhAnh->ha_ten) }}",146 @endforeach147 ],148 initialPreviewConfig: [149 @foreach($sp->hinhanhlienquan()->get() as $index=>$hinhAnh)150 {151 caption: "{{ $hinhAnh->ha_ten }}", 152 size: {{ Storage::exists('public/photos/' . $hinhAnh->ha_ten) ? Storage::size('public/photos/' . $hinhAnh->ha_ten) : 0 }}, 153 width: "120px", 154 url: "{$url}", 155 key: {{ ($index + 1) }}156 },157 @endforeach158 ]159 });160 });161</script>162 163<!-- Các script dành cho thư viện Mặt nạ nhập liệu InputMask -->164<script src="{{ asset('vendor/input-mask/jquery.inputmask.min.js') }}"></script>165<script src="{{ asset('vendor/input-mask/bindings/inputmask.binding.js') }}"></script>166 167<script>168 $(document).ready(function() {169 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Giá gốc170 $('#sp_giaGoc').inputmask({171 alias: 'currency',172 positionCaretOnClick: "radixFocus",173 radixPoint: ".",174 _radixDance: true,175 numericInput: true,176 groupSeparator: ",",177 suffix: ' vnđ',178 min: 0, // 0 ngàn179 max: 100000000, // 1 trăm triệu180 autoUnmask: true,181 removeMaskOnSubmit: true,182 unmaskAsNumber: true,183 inputtype: 'text',184 placeholder: "0",185 definitions: {186 "0": {187 validator: "[0-9\uFF11-\uFF19]"188 }189 }190 });191 192 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Giá bán193 $('#sp_giaBan').inputmask({194 alias: 'currency',195 positionCaretOnClick: "radixFocus",196 radixPoint: ".",197 _radixDance: true,198 numericInput: true,199 groupSeparator: ",",200 suffix: ' vnđ',201 min: 0, // 0 ngàn202 max: 100000000, // 1 trăm triệu203 autoUnmask: true,204 removeMaskOnSubmit: true,205 unmaskAsNumber: true,206 inputtype: 'text',207 placeholder: "0",208 definitions: {209 "0": {210 validator: "[0-9\uFF11-\uFF19]"211 }212 }213 });214 215 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Ngày tạo mới216 $('#sp_taoMoi').inputmask({217 alias: 'datetime',218 inputFormat: 'yyyy-mm-dd' // Định dạng Năm-Tháng-Ngày219 });220 221 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Ngày cập nhật222 $('#sp_capNhat').inputmask({223 alias: 'datetime',224 inputFormat: 'yyyy-mm-dd' // Định dạng Năm-Tháng-Ngày225 });226 });227</script>228 229@endsectionStep 6: hiệu chỉnh action update của Backend\SanPhamController
Bổ sung chức năng Lưu trữ cùng lúc nhiều hình ảnh
php
1/**2 * Update the specified resource in storage.3 *4 * @param \Illuminate\Http\Request $request5 * @param int $id6 * @return \Illuminate\Http\Response7 */8public function update(Request $request, $id)9{10 // Bổ sung ràng buộc Validate11 $validation = $request->validate([12 'sp_hinh' => 'file|image|mimes:jpeg,png,gif,webp|max:2048',13 14 // Cú pháp dùng upload nhiều file15 'sp_hinhanhlienquan.*' => 'image|mimes:jpeg,png,gif,webp|max:2048'16 ]);17 18 // Tìm object Sản phẩm theo khóa chính19 $sp = SanPham::where("sp_ma", $id)->first();20 $sp->sp_ten = $request->sp_ten;21 $sp->sp_giaGoc = $request->sp_giaGoc;22 $sp->sp_giaBan = $request->sp_giaBan;23 $sp->sp_thongTin = $request->sp_thongTin;24 $sp->sp_danhGia = $request->sp_danhGia;25 $sp->sp_taoMoi = $request->sp_taoMoi;26 $sp->sp_capNhat = $request->sp_capNhat;27 $sp->sp_trangThai = $request->sp_trangThai;28 $sp->l_ma = $request->l_ma;29 30 // Kiểm tra xem người dùng có upload hình ảnh Đại diện hay không?31 if ($request->hasFile('sp_hinh')) {32 // Xóa hình cũ để tránh rác33 Storage::delete('public/photos/' . $sp->sp_hinh);34 35 // Upload hình mới36 // Lưu tên hình vào column sp_hinh37 $file = $request->sp_hinh;38 $sp->sp_hinh = $file->getClientOriginalName();39 40 // Chép file vào thư mục "photos"41 $fileSaved = $file->storeAs('public/photos', $sp->sp_hinh);42 }43 44 // Lưu hình ảnh liên quan45 if ($request->hasFile('sp_hinhanhlienquan')) {46 // DELETE các dòng liên quan trong table `HinhAnh`47 foreach ($sp->hinhanhlienquan()->get() as $hinhAnh) {48 // Xóa hình cũ để tránh rác49 Storage::delete('public/photos/' . $hinhAnh->ha_ten);50 51 // Xóa record52 $hinhAnh->delete();53 }54 55 $files = $request->sp_hinhanhlienquan;56 57 // duyệt từng ảnh và thực hiện lưu58 foreach ($request->sp_hinhanhlienquan as $index => $file) {59 60 $file->storeAs('public/photos', $file->getClientOriginalName());61 62 // Tạo đối tưọng HinhAnh63 $hinhAnh = new HinhAnh();64 $hinhAnh->sp_ma = $sp->sp_ma;65 $hinhAnh->ha_stt = ($index + 1);66 $hinhAnh->ha_ten = $file->getClientOriginalName();67 $hinhAnh->save();68 }69 }70 $sp->save();71 72 // Hiển thị câu thông báo 1 lần (Flash session)73 Session::flash('alert-info', 'Cập nhật thành công ^^~!!!');74 75 // Điều hướng về trang index76 return redirect()->route('admin.sanpham.index');77}Step 7: hiệu chỉnh action despoy của Backend\SanPhamController
Bổ sung chức năng Xóa cùng lúc nhiều hình ảnh
php
1/**2 * Remove the specified resource from storage.3 *4 * @param int $id5 * @return \Illuminate\Http\Response6 */7public function destroy($id)8{9 // Tìm object Sản phẩm theo khóa chính10 $sp = SanPham::where("sp_ma", $id)->first();11 12 // Nếu tìm thấy được sản phẩm thì tiến hành thao tác DELETE13 if (empty($sp) == false) {14 15 // DELETE các dòng liên quan trong table `HinhAnh` 16 foreach ($sp->hinhanhlienquan()->get() as $hinhAnh) {17 // Xóa hình cũ để tránh rác 18 Storage::delete('public/photos/' . $hinhAnh->ha_ten);19 20 // Xóa record 21 $hinhAnh->delete();22 }23 24 // Xóa hình cũ để tránh rác25 Storage::delete('public/photos/' . $sp->sp_hinh);26 }27 $sp->delete();28 29 // Hiển thị câu thông báo 1 lần (Flash session)30 Session::flash('alert-info', 'Xóa sản phẩm thành công ^^~!!!');31 32 // Điều hướng về trang index33 return redirect()->route('admin.sanpham.index');34}
