php-laravelHow do I upload an image using PHP and Laravel?
To upload an image using PHP and Laravel, you need to follow the steps below:
- Create a form in your Laravel view file with an input type of file:
<form action="{{ route('image.upload') }}" method="POST" enctype="multipart/form-data">
<input type="file" name="image">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
- Create a route to handle the form submission in your routes/web.php file. The route should point to a controller function that will handle the upload:
Route::post('/image/upload', 'ImageController@upload')->name('image.upload');
- Create a controller to handle the form submission. The controller function should validate the image and then store it to the public/images folder:
public function upload(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('images'), $imageName);
return back()
->with('success','Image Uploaded successfully.')
->with('path',$imageName);
}
- Finally, you can access the uploaded image in your view file using the path stored in the session:
@if (session()->has('path'))
<img src="{{ asset('images/' . session()->get('path')) }}" alt="">
@endif
Helpful links
More of Php Laravel
- How can I use the @yield directive in PHP Laravel?
- How do I set up a Laravel worker using PHP?
- How do I run a seeder in Laravel using PHP?
- How can I use PHP Laravel and MongoDB together?
- How do I add a logo to a Laravel application using PHP?
- How do I use the "WHERE LIKE" clause in PHP Laravel?
- How can I use PHP, Laravel, and Vue together to create a web application?
- How do I use Redis with Laravel in PHP?
- How do I use PHP Laravel to validate a request?
- How can I use PHP Laravel or Magento to develop a software application?
See more codes...