xử lý cả 2 trường hợp: chọn ảnh từ URL và upload file thật (ok)
🔹 1. Trong Form View
Bạn có thể cho phép chọn 1 trong 2:
Hoặc chọn từ File Manager (URL)
Hoặc upload file thật
{{-- Chọn ảnh từ File Manager --}}
<label>Hình đại diện (URL)</label>
<div class="input-group mb-3">
<input id="thumbnail" class="form-control" type="text" name="featured_image_url" value="{{ old('featured_image_url', $post->featured_image_url ?? '') }}">
<button type="button" class="btn btn-secondary" onclick="openLfm()">Chọn ảnh</button>
</div>
<img id="holder" src="{{ old('featured_image_url', $post->featured_image_url ?? '') }}" style="max-height: 100px">
{{-- Upload ảnh từ máy --}}
<label>Hoặc upload ảnh (file)</label>
<input type="file" name="featured_image_file" class="form-control">
2. Trong Controller
Bạn xử lý như sau để ưu tiên ảnh được upload, nếu không thì dùng URL:
public function store(Request $request) { $data = $request->validate([ 'featured_image_url' => 'nullable|url', 'featured_image_file' => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048', // các rule khác... ]);
if ($request->hasFile('featured_image_file')) {
$path = $request->file('featured_image_file')->store('posts', 'public');
$featuredImage = 'storage/' . $path;
} elseif (!empty($data['featured_image_url'])) {
$featuredImage = $data['featured_image_url'];
} else {
$featuredImage = null;
}
Post::create([
// các dữ liệu khác...
'featured_image' => $featuredImage,
]);
return redirect()->route('admin.posts.index')->with('success', 'Bài viết đã được tạo');
}
Bạn chỉ cần 1 cột trong database: featured_image
, chứa hoặc đường dẫn nội bộ (storage/posts/xxx.jpg
) hoặc URL (https://...
).
3. Trong View hiển thị ảnh (ví dụ show.blade.php)
@if ($post->featured_image)
@if(Str::startsWith($post->featured_image, ['http://', 'https://']))
<img src="{{ $post->featured_image }}" alt="Ảnh đại diện" class="img-thumbnail">
@else
<img src="{{ asset($post->featured_image) }}" alt="Ảnh đại diện" class="img-thumbnail">
@endif
@else
<img src="{{ asset('assets/images/default.jpg') }}" alt="Ảnh mặc định" class="img-thumbnail">
@endif
Chú ý: Nếu featured_image
bắt đầu bằng http
, thì dùng trực tiếp. Nếu không, thì dùng asset()
để dẫn tới storage/
.
PreviousGộp toàn bộ phần khởi tạo CKEditor và xử lý ảnh vào 1 file JS riêngNextHiển thị ảnh có chứa https, http và không chứa https, http (ok)
Last updated
Was this helpful?