ali2535's avatar

how to upload image in laravel

how i can upload image in laravel? follow code is wrong?

      $image = $request->file('cover_image');
    $filename = $image->getClientOriginalName();

    $year = Carbon::now()->year;
    $imagePath = "upload/images/products/{$year}/";

    $uploaded = $image->move(public_path($imagePath), $filename);

    $product = Product::create(array_merge($request->all(), ['cover_image' => 
              $uploaded]));

in this code save image address in database by physical hard address (C:/wamp/www .....)

it is wrong and i can not show image. why ?

0 likes
6 replies
AddWebContribution's avatar

You should try this:

$image = $request->file('cover_image');
$filename = $image->getClientOriginalName();

$year = Carbon::now()->year;


$uploaded = $image->move(public_path().'upload/images/products/'.$year, $filename);

$product = Product::create(array_merge($request->all(), ['cover_image' => 
          $filename]));

Hope this work for you !!!

Snapey's avatar

Because you have to remember there are two ways to get to an image.

There is the path (c:/wamp/www/,,,,), which is what your web server uses to interact with the filesystem

Then there is the URL. The URL is what the outside world use to request the image (/upload/images/products/2016/mugshot.jpg)

The url is relative to the root of the public folder of project (the document root)

If you store the full path to the image in the database then you will have problems extracting the bits you need for the URL

public_path() is a helper for the public folder but does not belong in the URL.

If you change your code slightly, you should get what you want;

    $image = $request->file('cover_image');
    $filename = $image->getClientOriginalName();

    $year = Carbon::now()->year;
    $imagePath = "upload/images/products/{$year}/";

    $uploaded = $image->move(public_path($imagePath), $filename);

    $product = Product::create(array_merge($request->all(), ['cover_image' => $imagePath . $filename]));
ali2535's avatar

@saurabh => No this is wrong .

@Snapey => i removed public_path() but when save my image a error occured for example "upload/images\2.jpg"

instead of / save \ and this wrong

Snapey's avatar

i did not say remove public_path ?

ali2535's avatar

@Snapey i want save product image and show in page . how can i perform this?

Snapey's avatar

use the code i showed and then say why it does not work

But, make sure your environment is setup correctly and you don't see public in your urls

Please or to participate in this conversation.