Alia
Alia

Reputation: 1

Laravel: Retrieve image from database in Laravel 8?

I have a form where you can submit images. It checks it it is an an image and it saves it into the database. My issue is how do i view it? I don't know the url for the image.

The ImageController:

public function upload(Request $request)
    {
        
        $validatedData = $request->validate([
         'image' => 'required|image|mimes:jpg,png,jpeg,gif,svg|max:2048',
        ]);
        $name = $request->file('image')->getClientOriginalName();
        $path = $request->file('image')->store('public/images');
        $save = new Image;
        $save->name = $name;
        $save->path = $path;
        $save->save();
        return redirect('/')->with('mssg', 'Image Has been uploaded');
    }

Form:

@extends('layouts.app')
@section('content')
    <div class="wrapper adoption-details">
            <h1>Adoption for {{ $animal->name }}</h1>
            <img src="{{ asset('/image') }}" />
            <p>Name: {{ $animal->name }} </br>
               DoB: {{ $animal->dob }} </br>
               Availability: {{ $animal->available }} </br>
               Description: {{ $animal->description }} </br></p>
            
            <form name="image-upload" id="image-upload" method="post" action="{{url('upload')}}" enctype="multipart/form-data">
                 @csrf
        <div>
          <label for="choose">Please Select Image To Upload:</label>
          <input type="file" id="image" name="image" class="@error('image') is-invalid @enderror form-control">
          @error('image')
              <div class="alert alert-danger mt-1 mb-1">{{ $message }}</div>
          @enderror
        </div>
        <button type="submit" Submit="btn btn-primary">Submit</button>
      </form>
     </div>
    <a href="/animals" class="back">Back to all requests</a>
@endsection

What would be the <img src="{{ asset('/image') }}" /> be? The path of the image is storage/app/public/images/.

Upvotes: 0

Views: 1391

Answers (1)

lsek
lsek

Reputation: 15

You can configure your disk in config/filesystem.php. Something like this:

'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],

In .env file select default disk. You can configure many disks. Then save the path in database in column image (like a varchar) and add this column to SQL query. Remeber to add command php artisan storage:link then in blade use <img src="{{ Storage::url($animal->image) }}" />

Laravel documentation is very helpful. Read this Laravel Docs - Filesystem. I think you will find answer.

Upvotes: 2

Related Questions