0
votes

Well, what happens is that I want to upload an image to Cloudinary through Laravel, I Follow the steps as it says on the documentation:

https://github.com/cloudinary-labs/cloudinary-laravel and here : https://cloudinary.com/blog/laravel_file_upload_to_a_local_server_or_to_the_cloud

I am using Laravel 8, here is my code:

 public function store(Request $request){

    $request->validate([
        'name' => 'required|string|unique:festivals|max:255', //unique:table
        'description' => 'required|string|max:255',
        'image' => 'required|image|dimensions:min_width=200,min_height=200',
    ], self::$messages);

    //Here I create an instance and upload file to server 
    $festival = new Festival($request->all());
    $path = cloudinary()->upload($request->file('image')->getRealPath())->getSecurePath();
    dd($path);

    //Then at field image of festivals que save the path and that goes to the database
    $festival->image = 'festivals/' . basename($path);
    $festival->save();


    return response() -> json($festival, 201); //code 201 created

}

When I try to create a new record through Postman, this happens:

Error after register new festival

However, the image was uploaded to Cloudinary:

image uploaded

Then I tried to check if the record was created, but it was not created.

What can I do, does anyone know?

Thanks

1

1 Answers

0
votes

Ok, I Solved :)

    //Here I create an instance and upload file to server
    $festival = new Festival($request->all());
    $result = $request->image->storeOnCloudinary();
     
    //Here I get the url
    $path = $result->getPath();

    //Then at field image of festivals que save the path and that goes to the database

    //$festival->image = $path; output: "https://res.cloudinary.com/test/image/upload/v1226931211/zuiyb17vfs8dre6gvuov.jpg"
    //$festival->image = dirname($path); output: "https://res.cloudinary.com/test/image/upload/v1526711711"
    //$festival->image = basename($path); output: "zuiy31lvfs4dre5gvuov.jpg"
    $base =  basename(dirname($path).basename($path)); //output: "v1636941221zuiyb14vfsmdre6gvuov.jpg"
    $folder =  substr($base, 0, -24); //output: "v1626915261"
    //So:
    $img_path = $folder.'/'.basename($path);

    $festival->image = 'festivals/'.$img_path;  //imageFolder/imageName.jpg;

But if someone has a best way, please tell me