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();
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');
}`
I am using the stripe/stripe package to capture payment for single product. Everything is working as expected however when the user is returned to the order-confirmation page, I would like to get the stripe payment id. How would i achieve this?
Im not sure if i need a webhook and if i would, how would i use this?
public function onCharge() {
$user = Auth::getUser();
$course = CourseMeta::where('id', $this->param('id'))->first();
$stripe = new \Stripe\StripeClient(env('STRIPE_SECRET'));
$product = $stripe->products->create([
'name' => $course->course->name . ' - ' . $course->date,
]);
$price = $stripe->prices->create([
'unit_amount' => $course->price * 120,
'currency' => 'gbp',
'product' => $product->id,
]);
$validator = Validator::make(
[
'user_id' => $user->id,
'coursemeta_id' => $course->id,
'course_id' => $course->course->id,
'stripe_id' => '1',
],
[
'user_id' => 'required',
'coursemeta_id' => 'required',
'course_id' => 'required',
'stripe_id' => 'required'
]
);
if ($validator->fails()) {
return Redirect::back()->withErrors($validator);
} else {
$order = new Order();
$order->user_id = $user->id;
$order->coursemeta_id = $course->id;
$order->stripe_id = '1';
$order->company = request()->get('company');
$order->company_firstname = request()->get('company_firstname');
$order->company_lastname = request()->get('company_lastname');
$order->company_email = request()->get('company_email');
$order->company_phone = request()->get('company_phone');
$order->citb_levy = request()->get('citb_levy');
$order->d_firstname = request()->get('d_firstname');
$order->d_lastname = request()->get('d_lastname');
$order->d_email = request()->get('d_email');
$order->d_phone = request()->get('d_phone');
$order->d_dob = request()->get('d_dob');
$order->d_ninumber = request()->get('d_ninumber');
$order->save();
}
$portal = $stripe->checkout->sessions->create([
'success_url' => env('APP_URL') . '/order-confirmation'.'?' . 'user=' . $user->id . '&' . 'course=' . $course->id,
'cancel_url' => env('APP_URL') . '/cancel',
'line_items' => [
[
'price' => $price->id,
'quantity' => 1
],
],
'mode' => 'payment',
]);
return redirect($portal->url);
}
You need to use the checkout session ID.
when you create success_url and cancel_url you can also pass {CHECKOUT_SESSION_ID} param with curly braces. when payment gateway will redirect to one of those URLs it will automatically replace {CHECKOUT_SESSION_ID} with the actual session ID.
In your case
$portal = $stripe->checkout->sessions->create([
// HERE ---------------------------------------------------\/----------\/
'success_url' => env('APP_URL') . '/order-confirmation'.'?session_id={CHECKOUT_SESSION_ID}&' . 'user='. $user->id . '&' . 'course=' . $course->id,
'cancel_url' => env('APP_URL') . '/cancel',
'line_items' => [
[
'price' => $price->id,
'quantity' => 1
],
],
'mode' => 'payment',
]);
Now when this page is called you can have session ID and you can retrieve all stuff from it.
// on success or cancel page you can use this code to get infos
$stripe = new \Stripe\StripeClient(env('STRIPE_SECRET'));
$session = \Stripe\Checkout\Session::retrieve(get('session_id'));
$customer = \Stripe\Customer::retrieve($session->customer);
$paymentIntent = \Stripe\PaymentIntent::retrieve($session->payment_intent);
// from this $session you can get customer/items/paymentIntent etc..
ref : https://stripe.com/docs/payments/checkout/custom-success-page
if any doubt please comment.
I am having 2 methods. In one of the method I am making a call to database, a pure and simple one Document::findOrFail($data->id). But this is always returning me null although a record is already persisted. Any idea how to get this simple thing sorted?
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
public function downloadlockExport($token)
{
try {
$data = (object) Cache::get($token);
// dd I get the full $data as object
$document = Document::findOrFail($data->id);
// undefined. Above query did not execute.
// Thus, below query failed
$document->update(['downloads' => $document->downloads + 1]);
$content = Crypt::decrypt(File::get($data->file));
return response()->make($content, 200, array(
'Content-Disposition' => 'attachment; filename="' . basename($data->file) . '"'
));
} catch (\Exception $e) {
\App::abort(404);
}
}
What you probably would like to do is:
public function lockExport(Request $request){
$document = Document::create([
'user_id' => $this->userId(),
'extension' => $extension,
'name' => $filename,
'file_path' => $filepath,
'size' => File::size($filepath . $filename),
'received_at' => Carbon::now()->format('Y-m-d')
]);
$isAttachment = false;
$token = 'mytoken';
Cache::put($token, ['file' => $document->file_path . $document->name . '.' . $document->extension, 'is_attachment' => $isAttachment, 'id' => $document->id], 3);
return $this->downloadlockExport($token);
}
This way you will get your $token in your called function and you will get the $data correctly as I see.
And in the downloadlockExport() function you will have the ID like this:
$document = Document::findOrFail($data->mytoken['id']);
or you can use:
$document = Document::findOrFail($data->$token['id']);
similar with getting the File value:
$content = Crypt::decrypt(File::get($data->$token['file']));
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.');
}
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,