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
- ¿Cómo configurar PHP y Laravel desde cero?
- How do I set up a .gitlab-ci.yml file for a Laravel project using PHP?
- How can I find PHP Laravel jobs in Canada?
- How do I set up a Laravel HasMany relationship using PHP?
- How can I use PHP and Laravel together?
- How can I use PHP Laravel's ZipArchive library to create a zip file?
- How can I use the @yield directive in PHP Laravel?
- How can I get the current year in PHP Laravel?
- How do I configure Xdebug in the php.ini file for a Laravel project?
- How can I convert JSON data to XML using PHP Laravel?
See more codes...