NenTang.vn
Thiết kế Lập trình Web BackendThiết kế web với framework Laravel
Xây dựng danh mục Sản phẩm có chức năng upload hình ảnh - Edit
Chương 9 · Bài 9
Dự án thực tế mẫu - Trang web bán hàng trực tuyến - Thiết kế Backend
Thời lượng: 81 phútĐọc khoảng: 5 phút
Danh mục hình và bảng
Từ viết tắt
Nội dung bài học không khai báo từ viết tắt bằng thẻ abbr.
Nội dung bài học
Step 1: thực hiện tạo màn hình hiệu chỉnh Sản phẩm (edit)
Mô hình hoạt động của edit:
Viết code cho action edit($id):
- Action
edit($id)thường dùng để hiển thị màn hình bao gồm form và các ô nhập liệu (input). - Thông thường các ô nhập liệu (input) thường có sẵn giá trị ban đầu từ record trong database, để người dùng tự nhập thông tin vào.
- Trên màn hình sẽ có nút
Lưu
Hiệu chỉnh file app\Http\Controllers\Backend\SanphamController.php
php
1/**2 * Show the form for editing the specified resource.3 *4 * @param int $id5 * @return \Illuminate\Http\Response6 */7public function edit($id)8{9 // Sử dụng Eloquent Model để truy vấn dữ liệu 10 $sp = SanPham::where("sp_ma", $id)->first(); 11 $ds_loai = Loai::all(); 12 13 // Đường dẫn đến view được quy định như sau: <FolderName>.<ViewName> 14 // Mặc định đường dẫn gốc của method view() là thư mục `resources/views` 15 // Hiển thị view `backend.sanpham.edit` 16 return view('sanpham.edit')17 // với dữ liệu truyền từ Controller qua View, được đặt tên là `sp` và `danhsachloai`18 ->with('sp', $sp)19 ->with('danhsachloai', $ds_loai);20}Tạo view edit.blade.php
- Để dễ dàng quản lý các view, ta sẽ tạo 1 thư mục tương ứng với tên Controller, mỗi action sẽ tương ứng với tên view.
- Tạo folder
resources/views/sanpham - Tạo file
resources/views/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 <button type="submit" class="btn btn-primary">Lưu</button>82</form>83@endsection84 85@section('custom-scripts')86<!-- Các script dành cho thư viện bootstrap-fileinput -->87<script src="{{ asset('vendor/bootstrap-fileinput/js/plugins/sortable.js') }}" type="text/javascript"></script>88<script src="{{ asset('vendor/bootstrap-fileinput/js/fileinput.js') }}" type="text/javascript"></script>89<script src="{{ asset('vendor/bootstrap-fileinput/js/locales/fr.js') }}" type="text/javascript"></script>90<script src="{{ asset('vendor/bootstrap-fileinput/themes/fas/theme.js') }}" type="text/javascript"></script>91<script src="{{ asset('vendor/bootstrap-fileinput/themes/explorer-fas/theme.js') }}" type="text/javascript"></script>92 93<script>94 $(document).ready(function() {95 $("#sp_hinh").fileinput({96 theme: 'fas',97 showUpload: false,98 showCaption: false,99 browseClass: "btn btn-primary btn-lg",100 fileType: "any",101 append: false,102 showRemove: false,103 autoReplace: true,104 previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",105 overwriteInitial: false,106 initialPreviewShowDelete: false,107 initialPreviewAsData: true,108 initialPreview: [109 "{{ asset('storage/photos/' . $sp->sp_hinh) }}"110 ],111 initialPreviewConfig: [112 {113 caption: "{{ $sp->sp_hinh }}", 114 size: {{ Storage::exists('public/photos/' . $sp->sp_hinh) ? Storage::size('public/photos/' . $sp->sp_hinh) : 0 }}, 115 width: "120px", 116 url: "{$url}", 117 key: 1118 },119 ]120 });121 });122</script>123 124 125<!-- Các script dành cho thư viện Mặt nạ nhập liệu InputMask -->126<script src="{{ asset('vendor/input-mask/jquery.inputmask.min.js') }}"></script>127<script src="{{ asset('vendor/input-mask/bindings/inputmask.binding.js') }}"></script>128 129<script>130 $(document).ready(function() {131 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Giá gốc132 $('#sp_giaGoc').inputmask({133 alias: 'currency',134 positionCaretOnClick: "radixFocus",135 radixPoint: ".",136 _radixDance: true,137 numericInput: true,138 groupSeparator: ",",139 suffix: ' vnđ',140 min: 0, // 0 ngàn141 max: 100000000, // 1 trăm triệu142 autoUnmask: true,143 removeMaskOnSubmit: true,144 unmaskAsNumber: true,145 inputtype: 'text',146 placeholder: "0",147 definitions: {148 "0": {149 validator: "[0-9\uFF11-\uFF19]"150 }151 }152 });153 154 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Giá bán155 $('#sp_giaBan').inputmask({156 alias: 'currency',157 positionCaretOnClick: "radixFocus",158 radixPoint: ".",159 _radixDance: true,160 numericInput: true,161 groupSeparator: ",",162 suffix: ' vnđ',163 min: 0, // 0 ngàn164 max: 100000000, // 1 trăm triệu165 autoUnmask: true,166 removeMaskOnSubmit: true,167 unmaskAsNumber: true,168 inputtype: 'text',169 placeholder: "0",170 definitions: {171 "0": {172 validator: "[0-9\uFF11-\uFF19]"173 }174 }175 });176 177 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Ngày tạo mới178 $('#sp_taoMoi').inputmask({179 alias: 'datetime',180 inputFormat: 'yyyy-mm-dd' // Định dạng Năm-Tháng-Ngày181 });182 183 // Gắn mặt nạ nhập liệu cho các ô nhập liệu Ngày cập nhật184 $('#sp_capNhat').inputmask({185 alias: 'datetime',186 inputFormat: 'yyyy-mm-dd' // Định dạng Năm-Tháng-Ngày187 });188 });189</script>190 191@endsectionViết code cho action update($id):
- Action
update($id)thường dùng để thực thi câu lệnh UPDATE dữ liệu vào database. - Sẽ có kiểm tra ràng buộc ngoại lệ Validation.
- Sau khi Lưu dữ liệu thành công sẽ chuyển trang qua
index
Hiệu chỉnh file app\Http\Controllers\Backend\SanphamController.php
php
1use Storage;2use Session;3 4/**5 * Update the specified resource in storage.6 *7 * @param \Illuminate\Http\Request $request8 * @param int $id9 * @return \Illuminate\Http\Response10 */11public function update(Request $request, $id)12{13 // Bổ sung ràng buộc Validate14 $validation = $request->validate([15 'sp_hinh' => 'file|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 {33 // Xóa hình cũ để tránh rác34 Storage::delete('public/photos/' . $sp->sp_hinh);35 36 // Upload hình mới37 // Lưu tên hình vào column sp_hinh38 $file = $request->sp_hinh;39 $sp->sp_hinh = $file->getClientOriginalName();40 41 // Chép file vào thư mục "photos"42 $fileSaved = $file->storeAs('public/photos', $sp->sp_hinh);43 }44 $sp->save();45 46 // Hiển thị câu thông báo 1 lần (Flash session)47 Session::flash('alert-info', 'Cập nhật thành công ^^~!!!');48 49 // Điều hướng về trang index50 return redirect()->route('admin.sanpham.index');51}
