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
Related
i have this as my function in my controller
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
$config= ['table'=>'users', 'length'=>10, 'prefix'=>'ID'];
$user_id = IdGenerator::generate($config);
//save profile picture if added
if($data->hasfile('profile')){
$file = $data['profile'];
$extension = $file->getClientOriginalExtension();
$profile_pic = time().'.'.$extension;
$file->move(public_path('images/user/'),$profile_pic);
}
$user =User::create([
'id' => $user_id,
'fullname' => $data['fullname'],
'phonenumber' => $data['phonenumber'],
// 'profile_image' => $profile_pic,
'district_id' => $data['district_id'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
BusinessModel::create([
'user_id' =>$user_id,
'business_name' => $data['business_name'],
'category' => $data['category'],
// 'tax_clearance'=> $data['tax'],
// 'business_certificate'=> $data['cecrtificate'],
// 'ppda'=> $data['ppda'],
// 'other_docs'=> $data['otherdocs']
]);
return($user);
}
the commented lines contains input type of file so when i try using hasfile() am getting an error expected type object found an array.
how do i fix this and get the files from the form and inserting them into the database.
Try adding request inside a function parameter like this, hope this will help
protected function create(request $data)
You are getting multiple files from your form , first check the input tag it should be like this.
name="photos[]" multiple
if you want to store multiple files.
Then in the controller
$files = $request->file('photos');
foreach($files as $file){
//your store logic here
}
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');
}
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.
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.
I have a {{ Form::textarea('name') }} for add an array.
In a controller I use:
$input = $request->all();
$name = explode(PHP_EOL, $input['name']);
$this->validate($request, [
'name' => Rule::unique('table1')->where(function ($query) {
global $name;
$query->whereIn('name', $name);
})
]);
But it does not work. How to validation array for unique values?
Sorry for my english.
The easy approach. If you want better control and ability to use this with the validate method then i'd suggest creating a custom validation rule.
$data = [
'name' => explode(PHP_EOL, $request->input('name'))
];
$validator = \Validator::make($data, [
'name.*' => 'unique:table1,name',
]);
if ($validator->fails()) {
// Handle failed logic
}