Laravel Backend not getting files from form - laravel

I am trying to upload multiple files, and in the process there should be a temporary storage which is later on deleted.
In my blade file, I have the following:
<form action="/logo/post" method="POST" enctype="multipart/form-data">
#csrf
<input type="file"
class="filepond"
name="files[]"
id="files"
multiple
data-allow-reorder="true"
data-max-file-size="3MB"
data-max-files="3">
</form>
So, in name, I have files[] and on my id I have files.
In my UploadController where I am handling the temporary upload I am making use of the following function:
public function store(Request $request){
$input = $request->all();
$files=array();
if($filesUp=$request->file('files')){
foreach($filesUp as $file){
$name = $file->getClientOriginalName();
$folder = uniqid() . '-' . now()->timestamp;
$file->storeAs('/files/tmp/' . $folder, $name);
$files[]=$name;
TemporaryFile::create([
'folder' => $folder,
'filename' => $name
]);
}
return $folder;
}
return '';
}
So, everything goes fine by now, but the issue appears when I try to make use of this in the other controller. The other controller is NOT getting the files, I tried dd to check if it's getting any files, and it says null.
This is the code in the other controller:
public function store(Request $request){
$request->validate([
'title' => 'required|string|max:255',
'color' => 'required|string|max:7',
'description' => 'required|string|max:255',
'price' => 'required|numeric|between:0,99999.99',
]);
$logo = new Logo([
'user_id' => Auth::user()->id,
'category_id' => 1,
'title' => $request->title,
'color' => $request->color,
'description' => $request->description,
'price' => $request->price,
]);
$logo->save();
$files=array();
if($filesUp=$request->file('files')){
foreach($filesUp as $file){
$temporaryFile = TemporaryFile::where('folder', $file)->first();
if($temporaryFile){
$name = $file->getClientOriginalName();
$folder = uniqid() . '-' . now()->timestamp;
$file->storeAs('/files/' . $folder, $name);
$files[]=$name;
rmdir(storage_path('app/public/files/tmp/' . $file));
$temporaryFile->delete();
File::create([
'logo_id' => $logo->id,
'name' => $name
]);
}
}
}
}
Why is the other controller not getting any files?

Upload controller and other controller is accessed in which way? From form it is first going to upload controller and returning to form then going to other controller? If so check if image upload field getting empty after returning from upload controller to the form to submit to the other controller. Better you show your form also.

You can bring the files back to the form when returning to form after temporary save controller, and submit to original one

CHECK!!! your config on php.ini
may be, like me, is desactivated.

Related

Laravel form image not getting recognized as file

I'm making an edit page for users using Vue + Laravel rest-api and I'm having a hard time linking an image to the image field of the users table.
The first issue is that it's not recognizing the image as a file despite adding enctype="multipart/form-data" to the form. I looked up some solutions, but haven't found something useful.
The console.log(this.form.newimage) results in newimage: "data:image/jpeg;base64,/9j/4AAQS... so I pressume the format of it is good.
Backend UserController:
public function update(Request $request, $id) {
$validatedData = $request->validate([
'name' => 'nullable|string|max:255',
'email' => 'required|string|email|max:255|unique:users,email,'.$id,
'phone' => 'nullable|numeric|digits_between:5,15',
'address' => 'nullable|string|max:255',
'postal_code' => 'nullable|numeric|digits_between:3,200',
'country_id' => 'nullable|string|max:255',
'image' => 'nullable',
'newimage' => 'nullable|file',
]);
$data = array();
(...)
if($request->hasFile('newimage')) {
$destination_path = 'public/images';
$avatar = $request->file('newimage');
$imagename = $avatar->getClientOriginalName();
$path = $request->file('newimage')->storeAs($destination_path, $imagename);
$data['image'] = $filename;
}
User::where('id', $id)->update($data);
}
use store file fun
if($request->image)
{
$request->file('image')->store('image','public');
}

Laravel update request validation not working on 9.x

I have create a validation request file on request folder. It working fine in new insert. But when i update, it's not working also i pass the unique $id but not working.
a. Resource controller update method
public function update(KlassNameRequest $request, $id)
{
$validated = $request->validated();
KlassName::where('id', $id)->update($validated);
}
b. Validation code
public function rules()
{
return [
'name' => 'required|unique:klass_names|max:128,' . $this->id,
'ref' => 'required|unique:klass_names|numeric|between:1,999,' . $this->id,
'seat_quota' => 'required|numeric|between:1,9999',
'division' => 'required',
'semester' => 'required',
];
}
This message shows me when i update
return [
'name' => 'required|unique:klass_names,' . $this->id.'|max:128',
'ref' => 'required|unique:klass_names,' . $this->id.'|numeric|between:1,999',
'seat_quota' => 'required|numeric|between:1,9999',
'division' => 'required',
'semester' => 'required',
];
Just try this one
'name' => ['required','max:128',Rule::unique('klass_names')->where(function ($query) {
return $query->where('name', $this->name);
})],
'ref' => ['required','max:128',Rule::unique('klass_names')->where(function ($query) {
return $query->where('ref', $this-> ref);
})],
Hope it will solve the problem 😊
I have solve my problem in this way -
a. Add extra input hidden field passing id for $request method. Because my route is resource group route -
<form action="{{ route('adm.kls.update', $kls->id) }}" method="post">
#csrf
#method('PUT')
<input type="hidden" name="id" value="{{ $kls->id }}">
</form>
b. Some editing in validation code.
public function rules() {
return [
'name' => 'required|max:128|unique:klass_names,name,' . $this->id,
'ref' => 'required|numeric|between:1,999|unique:klass_names,ref,' . $this->id,
'seat_quota' => 'required|numeric|between:1,9999',
];
}
done.

Laravel upload image from API

I'm trying to upload an image using the API. Even though, after running the first test, the database just stored the directory and not the file-name, worst part, it stored all directories that come before the one that is needed to store the image.
The code I'm using for the store is the following one:
public function store(Request $request)
{
$image = $request->file('image');
if($image == null){
$imagesDir = 'subjectImgs/';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
$fileDir = $images[array_rand($images)];
$path = $fileDir;
} else {
$path = $image->storeAs('uploads/images/store/', $image->getClientOriginalName(), 'public');
}
$subject = new Homework([
'subject_id' => $request->subject_id,
'user_id' => auth()->user()->id,
'title' => $request->name,
'image' => $path,
'progress' => $request->progress,
'description' => $request->description,
'duedate' => $request->date
]);
$subject->save();
return response()->json([
"code" => 200,
"message" => "Homework added successfully"
]);
}
I'm uploading from a mobile device, I believe this info is also important (?) Same issue when in the simulator.
You are saving $path into $subject->image that is equal to public_path() . '/uploads/images/store/';. You should add $file->getClientOriginalName() if you want the filename :
$subject = new Homework([
...
'image' => $path . $file->getClientOriginalName(),
...
]);
You are settings 'image' => $path, and before that $path = public_path() . '/uploads/images/store/'; which yields the expected results.
Now if you want to only save from a form input, you can use the following code:
$image = $request->file('image');
$path = $image->storeAs('uploads/images/store/', $image->getClientOriginalName(), 'public');
Where 'public' is the default public filesystem as described in the doc here: https://laravel.com/docs/7.x/filesystem#the-public-disk

Laravel How to save path of img on db

Question: how i can store the path on table posts-> path
$path = public_path('image').$imageName; doesn't work
Controller
public function store(Request $request)
{
$this->validate(request(),[
'title' => 'required',
'image' => 'image|mimes:jpeg,png,jpg,gif,svg',
'body' => 'required',
]);
$imageName = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path('image'), $imageName);
auth()->user()->publish(
new Post(request(['title','body', 'path']))
);
session()->flash('message', 'your post has now been published');
return redirect('/');
}
This is how i would approach it:
Your validation request was wrong also its not request() see below:
public function store(Request $request, Post $post)
{
$this->validate($request,[
'title' => 'required',
'image' => 'image|mimes:jpeg,png,jpg,gif,svg',
'body' => 'required',
]);
if($files=$request->file('image')){
$path = public_path('path/to/image/folder');
$name= $files->getClientOriginalName();
$files->move($path, $name);
}
$userid = Auth::user()->id;
$post->create([
'user_id' => $userid,
'title' => $request->get('title'),
'body' => $request->get('body'),
'path' => $name (for image)
]);
session()->flash('message', 'your post has now been published');
return redirect()->back();
}
If you'd rather store the path, change $name to $path and it'll save the path for you.
Note: the $request->get() may need to be changed to suit your name=" " fields from the form.
I would do it like this i think it's simpler
try {
$url = 'http://localhost:8000/storage/' . $request->file('picfile')->store('uploads/UserImage', 'public');
} catch (\Exception $e) {
return response()->json([$e->getMessage()], 501);
}
Where "uploads/UserImage" is the folder where it's going tp be stored
And $url i simply the URL
Make sure u form have enctype="multipart/form-data".
php artisan storage:link (this command create a symbolic link
"public/storage" to "storage/app/public" more info here).
Make sure u migration have column to link image. $table->string('image')->nullable();
Check u model post and add image to $fillable (mass assignment,
more info here)
Blade: Acces to img url {{ Storage::url($post->image) }}
I wish I had helped you.

How to validate multiple images input?

I have this function which will allow users to upload one image or more. I already create the validation rules but it keep returning false no matter what the input is.
Rules :
public function rules()
{
return [
'image' => 'required|mimes:jpg,jpeg,png,gif,bmp',
];
}
Upload method :
public function addIM(PhotosReq $request) {
$id = $request->id;
// Upload Image
foreach ($request->file('image') as $file) {
$ext = $file->getClientOriginalExtension();
$image_name = str_random(8) . ".$ext";
$upload_path = 'image';
$file->move($upload_path, $image_name);
Photos::create([
'post_id' => $id,
'image' => $image_name,
]);
}
//Toastr notifiacation
$notification = array(
'message' => 'Images added successfully!',
'alert-type' => 'success'
);
return back()->with($notification);
}
How to solve this ?
That's all and thanks!
You have multiple image upload field name like and add multiple attribute to your input element
<input type="file" name="image[]" multiple="multiple">
So that, your input is like array inside which there will be images.
Since there is different method for array input validation, see docs here.
So, you have to validate something like this:
$this->validate($request,[
'image' => 'required',
'image.*' => 'mimes:jpg,jpeg,png,gif,bmp',
]);
Hope,You understand

Resources