Laravel Image Handling using Storage Link

Kwabena Nana Acheampong - Sep 23 - - Dev Community

In this guide, I will walk you through the process of effectively saving and retrieving images in a Laravel full-stack application. This tutorial assumes you have an active and running Laravel project.

STEP-1: Create a Storage Link
Laravel provides a simple and secure way to store files through the storage system. Before saving images, we need to create a symbolic link from the public/storage directory to the storage/app/public directory. This is done using an artisan command:

php artisan storage:link
Enter fullscreen mode Exit fullscreen mode

This command creates a storage folder inside your public directory, allowing you to access stored images through URLs.

STEP-2: Use the Storage Facade in the Controller
To handle image uploads, we can utilize Laravel's Storage facade within the controller method responsible for processing the form submission. Below is an example of how to implement image uploading:

public function store(Request $request)
{
    try {
        // Define validation rules
        $rules = [
            "image" => "required|image|mimes:jpeg,png,jpg,gif,svg|max:2048",
        ];

        // Validate the request
        $validation = Validator::make($request->all(), $rules);
        if ($validation->fails()) {
            return back()->with('error', $validation->errors()->first())->withInput($request->all());
        }

        // Handle image upload
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $imageName = time() . "." . $image->getClientOriginalExtension();

            // Store the image in the public disk
            $filePath = "images/causes/$imageName";
            Storage::disk('public')->put($filePath, file_get_contents($image));

            // Save the image path in the database
            $model = ModelClass::create([
                "image" => $filePath,
            ]);

            return redirect()->back()->with('success', 'Record successfully created!');
        }

    } catch (\Exception $e) {
        // Log the error and return a generic message
        Log::error("ERROR_MESSAGE_CAUSES: " . $e->getMessage());
        return back()->with('error', 'Sorry, an error occurred. Please try again.');
    }
}


Enter fullscreen mode Exit fullscreen mode

In this method:

  • We first validate that an image has been uploaded and meets the size and format requirements.
  • The image is then saved in the storage/app/public/images/folder directory.
  • The image path is stored in the database for future retrieval.

STEP-3: Add a Laravel Accessor for Easy Image Retrieval
To make image retrieval more seamless, we can create an accessor in our model. This accessor will automatically append the correct storage URL to the image path when retrieving it.

public function getImageUrlAttribute()
{
    return $this->image ? Storage::url($this->image) : null;
}

Enter fullscreen mode Exit fullscreen mode

This accessor returns the full URL of the stored image, making it easy to display images in your views.

In your blade file you can retrieve the image using:

<img src="{{ config('services.app_url.domain') . $modelInstance->image_url }}" alt="No Image" width="100px">
Enter fullscreen mode Exit fullscreen mode

STEP-4: Configure the Application URL
To ensure images are correctly accessed from the public folder, you should also set the application URL properly in the config/services.php file. Append this to the return array:

"app_url" => [
    "domain" => env("APP_URL"),
],
Enter fullscreen mode Exit fullscreen mode

Make sure that your .env file contains the correct URL for your application:

APP_URL=http://localhost:8000
Enter fullscreen mode Exit fullscreen mode

This ensures that your application knows where to serve static assets like images.

Conclusion
By following these steps, you can efficiently handle image uploads and retrievals in a Laravel application using the storage link system. The symbolic link allows for seamless access to images, while the Storage facade makes handling file uploads both secure and straightforward.

. .
Terabox Video Player