shahr's avatar
Level 10

How to upload and save image file?

Why this code does not work?

public function store(CategoryRequest $request)
{
    if ($request->hasFile('image')) {
        $randomize = rand(111111, 999999);
        $extension = $request->file('image')->getClientOriginalExtension();
        $filename = $randomize . '.' . $extension;
        $image = $request->file('image')->move('images/categories/', $fileName);
    }
    Category::create([
        'name' => $request->name,
        'latin' => $request->latin,
        'parent_id' => $request->parent_id,
        'image' => $image ?? null,
    ]);
    return redirect()->route('categories.index');
}

This is the code that does not uploads and does not save.

0 likes
14 replies
automica's avatar

@oxbir if you use Request instead of CategoryRequest does it save and create new category then?

if it does, can you post the contents of CategoryRequest

Snapey's avatar

maybe;

  • You did not put enctype="multipart/form-data" in your form header
  • Your file upload input element is named something other than image
  • You have the multiple tag on your file input element
  • You don't actually call the store method
  • something happening in CategoryRequest
  • validation failed
  • image is too large for max upload size
  • image is too large for max post size
1 like
shahr's avatar
Level 10

@snapey

I added enctype="multipart/form-data" in my form tag now.

My code is does not uploads and only save in database.

automica's avatar

@oxbir so your code is creating the category but not handling the uploaded image?

Neeraj1005's avatar

@oxbir can you put your blade file and route? did you try just dd() you image file?

Snapey's avatar

Its probably storing the image (else you would get an error) its just saving it somewhere on your machine that you did not expect

shahr's avatar
Level 10

@michaloravec

Is it correct now?

public function store(CategoryRequest $request)
{
    $image = null;
    if ($request->hasFile('image')) {
        $randomize = rand(111111, 999999);
        $extension = $request->file('image')->getClientOriginalExtension();
        $filename = $randomize . '.' . $extension;
        $image = $request->image->store('images', $filename);
    }
    Category::create([
        'name' => $request->name,
        'latin' => $request->latin,
        'parent_id' => $request->parent_id,
        'image' => $image,
    ]);
    return redirect()->route('categories.index');
}
MichalOravec's avatar

Yeah it's seems to be. But what is your default disk? It's a public?

jlrdw's avatar

Also @oxbir you did look in the images/categories folder and the image is not there?

Snapey's avatar

where would you like to store the image?

Please or to participate in this conversation.