Home > OS >  How to upload and store an image in database laravel 7
How to upload and store an image in database laravel 7

Time:10-12

It's my first time trying to upload and store in db an image in laravel. I have a form where I want to upload, store in db and display image for food categories. I checked laravel documentation, other questions similar to mine, even watched youtube tutorials but I guess I got lost in those many ways to do it and I ended up don't understanding anything. I tried a few ways to do it but I got different error types. If someone here could help me with an exemple of how to do it I would be really grateful!

This is what I have in my controller in store function (before starting to try to upload, store in db and display the image):

public function store(Request $request) {

    $category = new \App\Category();
    $category->title = $request->get('title');
    $category->imagename = $request->get('imagename');
    $category->featured = $request->has('featured');
    $category->active = $request->has('active');
    $category->save();


    session()->flash('success', "Category '{$category->title}' has been created.");
    return redirect()->route('category.index');
}

and this is the html in create.blade:

<form method="post" enctype="multipart/form-data" action="{{ route('category.store') }}" >
    <label for="title">Title</label><br>
    <input type="text" name="title" placeholder="Enter title" value="{{old('title')}}"><br>
    <label for="imagename">Image</label><br>
    <input type="file" name="imagename" id="imagename"><br>
    <label for="featured">Featured</label><br>
    <input type="checkbox" name="featured" value="1"><br>
    <label for="active">Active</label><br>
    <input type="checkbox" name="active" value="1"><br>
    <input type="hidden" name="_token" value="{{ csrf_token() }}" /><br>
    <input type="submit" name="submit" value="Add Category" class="btn-secondary">
</form>

CodePudding user response:

First of all you need to configure your storage configuration, on config/filesystems.php. By default files are going to be upload at storage/app/public, and in your function for save images you can use method storeAs().

But on database you gonna store the image route, as the following example code:

$format = $file->getClientOriginalExtension();
            //generate file name
            $fileName = time() . rand(1, 999999) . '.' . $format;

            // generate route name   $filename
            $path = 'storage/' . $fileName;
            //store file
            $file->storeAs('public/posts', $fileName);

            $create = $postImage->create([
                'name' => $fileName,
                'format' => $format,
                'url' => $path,
                'path' => $path,
            ]);

You can check this Laravel documentation page if you need more info about the process.

CodePudding user response:

Uploading base64 file to DB that will increase the DB size

$ImageObject = $ImageGallery::find($galleryId);     
$ImageObject->galleryContent= base64_decode($request->image);
$ImageObject->save();

the best thing is to upload files to local storage or other static storage.

Laravel provides a powerful filesystem abstraction thanks to the wonderful Flysystem PHP package by Frank de Jonge. The Laravel Flysystem integration provides simple to use drivers for working with local filesystems, Amazon S3, and Rackspace Cloud Storage. Even better, it's amazingly simple to switch between these storage options as the API remains the same for each system.

Reference: https://laravel.com/docs/5.8/filesystem

there you can upload files to disk it can be public/local/S3 other.

by default laravel provides uploading file to disk like this

$fileName = 'filenamewith full path & extension';
$scope = 'public/private/limited';
$content = base64_encode($content);
Storage::disk('local')->put($fileName,$content,$scope); // Uploading to local disk
Storage::disk('s3')->put($fileName,$content,$scope); // Uploading to S3 Bucket 

you can change the configuration from filesystems.php ( config->filesystems.php)

    'disks' => [

    'local' => [
        'driver' => 'local',
        'root' => storage_path('app').'/aws/',
    ],

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

    's3' => [
        'driver' => 's3',
        'key' => env('AWS_ACCESS_KEY_ID'),
        'secret' => env('AWS_SECRET_ACCESS_KEY'),
        'region' => env('AWS_DEFAULT_REGION'),
        'bucket' => env('AWS_BUCKET'),
        'url' => env('AWS_URL'),
    ],
],

That's it.

CodePudding user response:

As @Alberto Sinigaglia mentioned it's not recommended to store an image directly in the database, however there are a few methods of doing it. One of which is to convert it to a base64 string and then store the string like so...

$category->imagename = base64_encode(file_get_contents($request->file('imagename')->pat‌​h()));
$category->save();

A better way of doing it would be to store the image on your server using Laravel and then save the public url to the database...

//Store image in public folder
$image = $request->file('imagename')->store('public');

//Save url to image
$category->imagename = asset($image);
$category->save();

Variations of this method are here in the documentation https://laravel.com/docs/8.x/filesystem#file-uploads

  • Related