I've got problem setting the avatar name so I can put to the database, it shows an object and not the filename, as you can see I've echo $filename to make sure I've got the name of the image. but when I print_r($sanitized), the image is an object.
My expected result of $sanitized should be:
Array
(
[email] => superadmin#email.com
[name] => Superadmin
[phone] => 123123
[avatar] => 1_avatar1546579727.jpg
)
Code:
public function updateProfile(Request $request)
{
$this->setUser($request);
$user = $this->user;
// Validate the request
$this->validate($request, [
'email' => ['sometimes', 'email', Rule::unique('users', 'email')->ignore($this->user->getKey(), $this->user->getKeyName()), 'string'],
'name' => ['nullable', 'string'],
'phone' => ['sometimes', 'string'],
'avatar' => ['sometimes', 'image', 'mimes:jpeg,png,jpg,gif', 'dimensions:min_width=500,min_height=500', 'max:2048'],
], [
'avatar.mimes' => 'Uploaded file format should be jpeg, jpg, png or gif.',
'avatar.dimensions' => 'Image should have minimum 200x200px dimensions.',
'avatar.max' => 'Maximum allowed file size is 2 MB.',
]);
if($request->hasFile('avatar')) {
$filename = $user->id.'_avatar'.time().'.'.request()->avatar->getClientOriginalExtension();
Image::make(request()->avatar)->resize(300, 300)->save( public_path('uploads/avatars/'.$filename) );
// $request->avatar = $filename;
$request['avatar'] = $filename;
}
// Sanitize input
$sanitized = $request->only([
'email',
'name',
'phone',
'avatar'
]);
echo $filename . "</br>";
echo "<pre>";
print_r( $sanitized );
echo "</pre>";
return "";
// $this->user->update($sanitized);
// return redirect()->back()->with('success', 'Profile has been updated.');
}
EDIT 1
I've tried all your answers, it still the same results.
Code:
if($request->hasFile('avatar')) {
$filename = $user->id.'_avatar'.time().'.'.request()->avatar->getClientOriginalExtension();
Image::make(request()->avatar)->resize(300, 300)->save( public_path('uploads/avatars/'.$filename) );
//This is what I've tried so far below:
$request->request->add(['avatar', $filename]);
// $request->merge(['avatar' => $filename]);
// $request->avatar = $filename;
// $request['avatar'] = $filename;
}
I've just fixed it by just giving me a hint of #Md.Sukel Ali
I've moved the $sanitzed = $request.. to the top, then update it and not using directly $request variable.
Working Code:
public function updateProfile(Request $request)
{
$this->setUser($request);
$user = $this->user;
// Validate the request
$this->validate($request, [
'email' => ['sometimes', 'email', Rule::unique('users', 'email')->ignore($this->user->getKey(), $this->user->getKeyName()), 'string'],
'name' => ['nullable', 'string'],
'phone' => ['sometimes', 'string'],
'avatar' => ['sometimes', 'image', 'mimes:jpeg,png,jpg,gif', 'dimensions:min_width=500,min_height=500', 'max:2048'],
], [
'avatar.mimes' => 'Uploaded file format should be jpeg, jpg, png or gif.',
'avatar.dimensions' => 'Image should have minimum 200x200px dimensions.',
'avatar.max' => 'Maximum allowed file size is 2 MB.',
]);
// Sanitize input
$sanitized = $request->only([
'email',
'name',
'phone',
'avatar'
]);
if($request->hasFile('avatar')) {
$filename = $user->id.'_avatar'.time().'.'.request()->avatar->getClientOriginalExtension();
Image::make(request()->avatar)->resize(300, 300)->save( public_path('uploads/avatars/'.$filename) );
$sanitized['avatar'] = $filename;
}
echo $filename . "</br>";
echo "<pre>";
print_r( $sanitized );
echo "</pre>";
return "";
// $this->user->update($sanitized);
// return redirect()->back()->with('success', 'Profile has been updated.');
}
Related
PLease help me on how to upload image in the folder and the same time in the database with a random name.
There's an error: Call to a member function getName() on null.
Heres my code in controller
`public function actionInsert()
{
$destination = new DestinationModel();
$name=$this->request->getVar('name');
$place=$this->request->getVar('place');
$location=$this->request->getVar('location');
$category=$this->request->getVar('category');
$description=$this->request->getVar('description');
$latitude=$this->request->getVar('latitude');
$longitude=$this->request->getVar('longitude');
$image=$this->request->getFile('image');
$imageName = $image->getName();
$image->move('im/destination', $imageName);
if($place == 'Calapan City')
{
$place = 'Calapan';
}else if($category == 'Destination')
{
$category ='Destination';
}
$data = [
'name' => $name,
'place' => $place,
'location' => $location,
'category' => $category,
'image' => $place. '/'. $imageName,
'description' => $description,
'latitude' => $latitude,
'longitude' => $longitude
];
$destination->save($data);
return view('adding_place');
}`
How can i upload a file and save the file using using original file name ?
Here my controller code ?
public function store(Request $request)
{
//Validate request data
$request->validate([
'name' => 'required',
'file' => 'required|mimes:pdf|max:50000',
'category' => 'required',
'year' => 'required|integer'
]);
$file = $request->file
$filename = Storage::disk('public')->putFile('regulations', $file);
Document::create([
'name' => $request->name,
'file' => $filename,
'category' => $request->category,
'year' => $request->year
]);
//redirect with success
return redirect()->back()->with('success', 'Done!');
}
Try this
$file = $request->file('file');
$file->getClientOriginalName();
I've a table of building in which there is building name in db.when i add building through blade if the building name exist then it can not added. instead of storing it to db i want to show some error.what should i do?
this is my validation
$validator = Validator::make(
$request->all(),
[
'b_name' => 'required|max:20',
],
[
'b_name.required' => '*please fill this field',
]
);
if ($validator->fails()) {
return Response::make([
'message' => trans('validation_failed'),
'errors' => $validator->errors(),
]);
}
if ($validator->passes()) {
$name = $request->input('b_name');
$description = $request->input('b_description');
$created_at = Carbon::now();
$updated_at = Carbon::now();
$array = array('name' => $name, 'description' => $description, 'created_at' => $created_at, 'updated_at' => $updated_at);
Building::insert($array);
$validator = Validator::make(
$request->all(),
[
'b_name' => 'required|max:20|unique:buildings,name',
],
[
'b_name.required' => '*please fill this field',
'b_name.unique' => ('*building name already exists'),
]
);
if ($validator->fails()) {
return Response::make([
'message' => trans('validation_failed'),
'errors' => $validator->errors(),
]);
}
if ($validator->passes()) {
$name = $request->input('b_name');
$description = $request->input('b_description');
$created_at = Carbon::now();
$updated_at = Carbon::now();
$array = array('name' => $name, 'description' => $description, 'created_at' => $created_at, 'updated_at' => $updated_at);
Building::insert($array);
return 1;
}
Response::json(['errors' => $validator->errors()]);
}
If b_name is your input for building name and name is your database field name for Building model then try this code in your validation.
'b_name' => 'required|max:20|unique:App\Building,name'
For more details visit : https://laravel.com/docs/6.x/validation#rule-unique
Your code shoulde be like
$input = $request->all();
$rules = ['b_name' => 'required|required|unique:table_name,b_name|max:20'];
$messages = [
'b_name.required' => '*please fill this field'
'b_name.unique' => 'building name already taken.'
];
$validator = Validator::make($input, $rules, $messages);
I'm new to laravel. I get the following error when uploading a file:
Call to a member function move() on null
$file = $request->file('img');
$destinationPath = base_path('\public\img');
$file->move($destinationPath . $file->getClientOriginalName());
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $request->get('img'),
]);
Why dont You Try it like this ?
if ($request->hasFile('img')) {
$image = $request->file('img');
$teaser_image = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $img);
} else {
dd('Request Has No File');
}
and For Your Store :
$dialer = Dialer::create([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $request->get('img') ?? null,
]);
You Can remove ??null for making sure that you get The image And store it in database but You can Even place It To make it Optional for the User To insert img or not . hope this helps
EDIT
According to your comment i guess you may have 2 problems :
first one be sure that you have and input that named 'img' that sends the image and the secound is that be sure to add the multi enctype to your form so that form can send image like below :
enctype="multipart/form-data"
so your form should be like this :
<form action="someRoute" method="post" enctype="multipart/form-data">
if ($request->hasFile('img')) {
$image = $request->file('img');
// print_r($image);
$image_name = time().'.'.$image->getClientOriginalExtension();
// echo $image;
// exit(0);
$destinationPath = base_path('Uploads');
$image->move($destinationPath, $image_name);
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $image_name,
]);
$dealer->save();
Session::flash('msg','Data Added successfully');
Session::flash('type','success');
return redirect('dealer-master');
// // echo $image;
// // exit(0);
// $destinationPath = base_path(' Uploads');
// $image->move($destinationPath, $image_name);
}
else {
Session::flash('msg','Please Check the data');
Session::flash('type','fail');
return redirect('dealer-master');
// echo $request;
}
I Findout my mistake This is working good Thank U Guys...!
It's work form me
if($request->img){
$fileName = time() . '.' . $request->img->extension();
$request->img->move(storage_path('app/public/img'), $fileName);
}
$dealer = new Dealer([
'firstname' => $request->get('firstname'),
'lastname' => $request->get('lastname'),
'email' => $request->get('email'),
'phoneno' => $request->get('phoneno'),
'img' => $fileName ?? null,
]);
$dealer->save();
What to here ?
how to assign the value of $filenameTosTor for my 'photo' which is a database column?
public function update(Request $request, User $user)
{
$filenameWithExt = $request->file('profile_pic')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
Get the Extention
$extention = $request->file('profile_pic')->getClientOriginalExtension();
$filenameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('profile_pic')->storeAs('public/profile_image', $filenameToStore);
$userupdate = User::where('id', $user->id)->update
([
'name' => $request->input('name'),
$user->profile_pic =$filenameToStore;
'photo'=> $request->($filenameToStore);
'last_name' => $request->input('last_name'),
'phone_number' => $request->input('phone_number'),
'address' => $request->input('address'),
'facebook_link' => $request->input('facebook_link'),
'twittr_link' => $request->input('twittr_link'),
'youtube_link' => $request->input('youtube_link'),
'Biography' => $request->input('Biography'),
]);
$userupdate->save();
return redirect('user.index');
}
Just use this variable like this:
'photo' => $filenameToStore,