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.
@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
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
@snapey
I added enctype="multipart/form-data" in my form tag now.
My code is does not uploads and only save in database.
@oxbir so your code is creating the category but not handling the uploaded image?
@oxbir can you put your blade file and route?
did you try just dd() you image file?
Its probably storing the image (else you would get an error) its just saving it somewhere on your machine that you did not expect
@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');
}
Yeah it's seems to be. But what is your default disk? It's a public?
Also @oxbir you did look in the images/categories folder and the image is not there?
where would you like to store the image?
Please or to participate in this conversation.