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']));
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.
The amount I'm passing seems correct, but I got always an error.
As I checkout the amount is invalid, even if I'm passing a float, and this error is shown on the page after submit:
The payment function is as following:
public function payment(Request $request) {
$data = $request->all();
// dd($data['price']);
$gateway = new Braintree\Gateway([
'environment' => config('services.braintree.environment'),
'merchantId' => config('services.braintree.merchantId'),
'publicKey' => config('services.braintree.publicKey'),
'privateKey' => config('services.braintree.privateKey')
]);
$amount = Sponsorship::where('price', $data['price'])->first();
// dd($amount);c
$nonce = $request->payment_method_nonce;
$result = $gateway->transaction()->sale([
'amount' => $amount,
'paymentMethodNonce' => $nonce,
'customer' => [
'firstName' => 'Tony',
'lastName' => 'Stark',
'email' => 'tony#avengers.com',
],
'options' => [
'submitForSettlement' => true
]
]);
if ($result->success) {
$transaction = $result->transaction;
// header("Location: transaction.php?id=" . $transaction->id);
return back()->with('success_message', 'Transaction successful. The ID is:'. $transaction->id);
} else {
$errorString = "";
foreach ($result->errors->deepAll() as $error) {
$errorString .= 'Error: ' . $error->code . ": " . $error->message . "\n";
}
// $_SESSION["errors"] = $errorString;
// header("Location: index.php");
return back()->withErrors('An error occurred with the message: '.$result->message);
}
}
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();
I want to save my images with using save_image() function in media model..
Here is my media model;
class Media extends Model
{
public function save_image($file)
{
$realname = str_slug(pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
$extension = $file->getClientOriginalExtension();
$new_name = str_slug($realname) . "-" . time() . "." . $extension;
$file->move(public_path('uploads'), $new_name);
$image = DB::create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
return $image;
}
}
in my controller;
public function storeMedia(Request $request)
{
$this->validate($request,[
'image'=> 'required|mimes:jps,png,gif,jpeg'
]);
$image=$request->file('image');
$media = new Media();
$media->save_image($image);
return response()->json([
'url'=> env('APP_URL')."/".$image->image_path,
'alt' => $image->image_alt_name,
'id' => $image->id,
]);
}
Are we have to say DB::table('media') at the first ? I mean, we are already on media model, is that necesary ?
You are not specifying the table name in your code.
Here is the Solution
$image = DB::table('media')->create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
OR
$image = Media::create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
You can also use $this->create
Hope this helps
Query builder doesn't have create() method, so you need to use Eloquent:
Model::create([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);
If you want to use query builder, you can use the insert() method:
DB::table('table_name')->insert([
'image' => $new_name,
'image_path' => "uploads/" . $new_name,
'image_alt_name' => $realname
]);