How to store an image with laravel?

Member

by lottie , in category: PHP Frameworks , 3 days ago

How to store an image with laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dana , 2 days ago

@lottie 

To store an image with Laravel, you can follow these steps:

  1. Create a file input in your HTML form to allow users to upload an image.
1
2
3
4
<form action="/upload-image" method="post" enctype="multipart/form-data">
    <input type="file" name="image">
    <button type="submit">Upload Image</button>
</form>


  1. Create a route in your routes/web.php file to handle the image upload.
1
2
3
use AppHttpControllersImageController;

Route::post('/upload-image', [ImageController::class, 'store']);


  1. Create a controller to handle the image upload logic.
1
php artisan make:controller ImageController


  1. In your ImageController, write the store method to store the image in the storage/app/public directory.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
use IlluminateSupportFacadesStorage;

public function store(Request $request)
{
    $image = $request->file('image');
    $imageName = $image->getClientOriginalName();
    
    Storage::putFileAs('public', $image, $imageName);

    return "Image uploaded successfully!";
}


  1. Update your filesystems.php configuration file to link the public disk to the storage/app/public directory.
1
2
3
4
5
6
'public' => [
    'driver' => 'local',
    'root' => storage_path('app/public'),
    'url' => env('APP_URL').'/storage',
    'visibility' => 'public',
],


  1. create a symbolic link from public/storage to storage/app/public.
1
php artisan storage:link


  1. Access the stored image using the following URL:
1
<img src="{{ asset('storage/' . $imageName) }}" alt="Image">


By following these steps, you can easily upload and store an image with Laravel.