How to avoid 504 Gateway Timeout with Laravel mass insert? - php

Connections can have 1,000 - 10,000 items passed to it. I keep getting a 504 when trying to hit this controller, I've changed it from individual Create to mass Insert (one query) but it still throws a 504 if connections are higher than 1000.
How can I improve this code to not throw a 504? I don't really want to expend that time from 60 seconds.
The function that takes the longest is storeConnections
<?php
declare(strict_types = 1);
namespace App\Http\Controllers\Api\Cache;
use App\Http\Controllers\Controller;
use App\Http\Requests\StoreCacheItemRequest;
use App\Models\CacheConnection;
use App\Models\CacheItem;
use App\Models\CacheMedia;
use App\Models\QueueItem;
use App\Models\QueueItemFailed;
use Illuminate\Http\Request;
class StoreController extends Controller
{
public function __invoke(StoreCacheItemRequest $request)
{
if (CacheItem::where('item', $request->get('item'))->exists())
{
return response()->json([
'error' => 'Cache item ' . $request->get('item') . ' already exists.'
], 500);
}
$cache = CacheItem::create([
'item' => $request->get('item'),
'name' => $request->get('name'),
'picture' => $request->get('picture'),
'description' => $request->get('description'),
'connection_count' => $request->get('connection_count'),
'is_private' => $request->get('is_private'),
'has_snap' => $request->get('has_snap', false),
'additional_data' => $request->get('additional_data'),
'type_id' => $request->get('type_id'),
]);
if ($request->has('connections')) {
$this->storeConnections($request->get('connections'), $cache->id);
}
if ($request->has('pictures')) {
$this->storeMedia($request->get('pictures'), $cache->id);
}
}
private function storeConnections($connections, $cacheId)
{
$connectionData = [];
foreach ($connections as $item) {
$queryData[] = [
'cache_id' => $cacheId,
'item' => $item
];
}
CacheConnection::insert($connectionData);
$queueData = [];
foreach ($queryData as $item) {
if (!QueueItem::where('item', $item)->exists() &&
!QueueItemFailed::where('item', $item)->exists() &&
!CacheItem::where('item', $item)->exists())
{
$queueData[] = [
'item' => $item,
];
}
}
Queue::insert($queueData);
}
private function storeMedia($media, $cacheId)
{
foreach ($media as $item) {
CacheMedia::create([
'cache_id' => $cacheId,
'item' => $item
]);
}
}
}

Related

I have a problem on API Resources Laravel (Maximum stack depth exceeded)

i have a problem when i use API Resources inside another API Resources class like this:
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
but when I remove the class the problem disappears like this :
if (! Route::is('job.*')) {
$data['sites']= $this->sites;
$data['jobs'] = $this->jobs;
}
this is -> image for error
this is my code :
class CustomerResource extends JsonResource
{
public function toArray($request)
{
$data = [
'id' => $this->id,
'name' => $this->name,
'billing_details' => $this->billing_details,
'billing_info' => [
'address' => $this->billing->address,
'street_num' =>$this->billing->street_num,
'country' =>$this->billing->country->name,
'city' =>$this->billing->city,
'postal_code' =>$this->billing->postal_code,
'credit_limit' =>$this->billing->credit_limit,
'payment_term_id' =>$this->billing->payment_term_id,
'send_statement' =>$this->billing->send_statement
],
'contacts' => $this->contacts,
'sitecontact' => $this->sitecontact,
];
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
return $data;
}
}
I called CustomerRessource class on JobRessource class which leads to an infinite loop between them
JobRessource class
if (! Route::is('job.*')) {
$data['sites']= SiteResource::collection($this->sites);
$data['jobs'] = JobResource::collection($this->jobs);
}
I fixed it by using this condition on JobRessource
if (Route::is('job.*')) {
$data['customer' ] = new CustomerResource($this->customer);
}
JobRessource with condition
#N69S thank you for your comment

An exception has been thrown during the rendering of a template ("Unable to resolve dependency [Parameter #0 [ $listing ]]")

I have decided to upgrade the Laravel framework version to resolve the critical security flaws. I have successfully upgraded from 5.8 to 6 and then to 6.20 (exploit fixed).
But unfortunately I have encountered an error starting from Laravel framework 6.19.0 which throws an exception in my class (BuyWidget.php) which is related to BoundMethod.php. I have checked through the internet and found out they implemented check for non specified types in BoundMethod.php (Illuminate\Container\BoundMethod).
I tried to change all the functions in BuyWidget.php accordingly: public function run($listing) to public function run(Listing $listing) etc.
BuyWidget.php
<?php
namespace App\Widgets\Order;
use Arrilot\Widgets\AbstractWidget;
use App\Models\Listing;
class BuyWidget extends AbstractWidget
{
protected $config = [];
public function calculate_price($listing, $params) {
$fee_percentage = setting('marketplace_percentage_fee');
$fee_transaction = setting('marketplace_transaction_fee');
$quantity = isset($params['quantity'])?$params['quantity']:1;
$variants = isset($params['variant'])?$params['variant']:null;
$shipping = isset($params['shipping_option'])?$params['shipping_option']:null;
$additional_options = isset($params['additional_option'])?$params['additional_option']:[];
$additional_options_meta = isset($params['additional_options_meta'])?$params['additional_options_meta']:[];
$listing_price = $listing->price;
#calculate additional variant cost
$selected_variant = null;
$error = false;
$user_choice = [];
$user_choice[] = ['group' => 'general', 'name' => 'quantity', 'value' => $quantity];
if($variants) {
$variant_pricing = $listing->variants;
foreach($variants as $k => $v) {
$variant_pricing = $variant_pricing->where("meta.$k", $v);
$user_choice[] = ['group' => 'variant', 'name' => $k, 'value' => $v];
}
if($variant_pricing->count() == 1) {
$selected_variant = $variant_pricing->first();
$listing_price += $selected_variant->price;
if($quantity > $selected_variant->stock) {
$error = __('Insufficient stock. Please lower the quantity.');
}
if($selected_variant->stock < 1) {
$error = __('Out of Stock');
}
}
}
#calculate shipping cost
$selected_shipping_price = null;
if(!is_null($shipping)) {
$selected_shipping_method = $listing->shipping_options->firstWhere('id', $shipping)?:null;
if($selected_shipping_method) {
$selected_shipping_price = $selected_shipping_method->price;
}
$user_choice[] = ['group' => 'shipping', 'name' => 'Shipping', 'value' => $selected_shipping_method->name, 'price' => $selected_shipping_method->price];
}
#additional pricing
$additional_options_price = $listing->additional_options->reduce(function ($carry, $item) use($additional_options, $additional_options_meta) {
if(in_array($item->id, array_keys($additional_options))) {
$price = $item->price;
$quantity = 1;
if(in_array($item->id, array_keys($additional_options_meta)) && isset($additional_options_meta[$item->id]['quantity'])) {
$quantity = (int) $additional_options_meta[$item->id]['quantity'];
}
return $carry + ($price*$quantity);
}
return $carry;
}, 0);
$number = 0;
foreach($listing->additional_options as $k => $item) {
if(in_array($item->id, array_keys($additional_options))) {
$number++;
$user_choice[] = ['group' => 'additional_options', 'name' => 'Option '.($k+1), 'value' => $item->name, 'price' => $item->price];
}
}
//date, time, qty
$subtotal = ($quantity * $listing_price) + $additional_options_price;
$service_fee_percentage = $subtotal * ($fee_percentage/100);
$service_fee = (float) $service_fee_percentage + (float) $fee_transaction;
$total = $subtotal + $service_fee + $selected_shipping_price;
if($quantity > $listing->stock) {
$error = __('Insufficient stock. Please lower the quantity.');
}
if($listing->stock < 1) {
$error = __('Out of Stock');
}
//now check if we have any slots left for this time
$price_items = [
[
'key' => 'price',
'label' => __(':price x :quantity :unit_label', ['price' => format_money($listing_price, $listing->currency), 'quantity' => $quantity, 'unit_label' => $listing->unit]),
'price' => ($quantity * $listing_price)
]
];
if($selected_shipping_price) {
$price_items[] = [
'key' => 'service',
'label' => __('Shipping'),
'price' => $selected_shipping_price,
];
}
if($additional_options_price) {
$price_items[] = [
'key' => 'additional',
'label' => __('Additional options'),
'price' => $additional_options_price,
];
}
if($service_fee > 0) {
$price_items[] = [
'key' => 'service',
'label' => __('Service fee'),
'price' => $service_fee,
'notice' => __('This fee helps cover the costs of operating the website'),
];
}
return [
'user_choice' => $user_choice,
'error' => $error,
'total' => $total,
'service_fee' => $service_fee,
'price_items' => $price_items,
];
}
public function decrease_stock($order, $listing)
{
$quantity = $order->listing_options['quantity'];
$listing->decrement( 'stock', $quantity );
if(isset($order->listing_options['variant'])) {
$variants = $order->listing_options['variant'];
$listing_variants = $listing->variants;
foreach($variants as $k => $v) {
$listing_variants = $listing_variants->where("meta.$k", $v);
}
if($listing_variants->count() == 1) {
$listing_variant = $listing_variants->first();
$listing_variant->decrement( 'stock', $quantity );
}
}
}
public function validate_payment($listing, $request)
{
$result = $this->calculate_price($listing, request()->all());
return $result;
}
/**
* Treat this method as a controller action.
* Return view() or other content to display.
*/
public function run($listing)
{
//
$total = 0;
$quantity = request('quantity', 1);
$result = $this->calculate_price($listing, request()->all());
return view('listing.widgets.buy_widget', [
'config' => $this->config,
'listing' => $listing,
'qs' => http_build_query(request()->all()),
'error' => $result['error'],
'total' => $result['total'],
'service_fee' => $result['service_fee'],
'price_items' => $result['price_items'],
]);
}
}
However after applying these changes the app does not work properly, the parameters are always empty and the product is shown as Out Of Stock.
The initial exception has been thrown at sidebar.twig file which builds up the widget based on the listing type.
"An exception has been thrown during the rendering of a template ("Unable to resolve dependency [Parameter #0 [ $listing ]] ")
sidebar.twig
{% if listing.pricing_model %}
{{ Widget.run('Order.'~(listing.pricing_model.widget)~'Widget', {}, listing) | raw }}
{% endif %}
Code works flawlessly on any other versions before Laravel 6.19.0. If I manually revert the changes from file BoundMethod.php the code works as expected even on never vesions. I would like to find another solution to avoid modifying vendor files, since it's not the best approach.
web.php
include "admin.php";
include "payments.php";
Route::get('/cp', function () {
if(env('DEMO_PANEL')) {
\Auth::loginUsingId(1, true);
return redirect("/panel");
}
});
Route::group(['prefix' => LaravelLocalization::setLocale(), 'middleware' => 'jailBanned'], function()
{
Auth::routes();
Route::get('email-verification', 'Auth\EmailVerificationController#sendEmailVerification')->name('email-verification.send');
Route::get('email-verification/error', 'Auth\EmailVerificationController#getVerificationError')->name('email-verification.error');
Route::get('email-verification/check/{token}', 'Auth\EmailVerificationController#getVerification')->name('email-verification.check');
Route::get('/', 'HomeController#index')->name('home');
Route::get('/browse', 'BrowseController#listings')->name('browse');
Route::get('/categories', 'BrowseController#categories')->name('categories');
Route::get('/pages/{slug?}', 'PageController#index')->name('page');
Route::get('/contact', 'ContactController#index')->name('contact');
Route::post('/contact', 'ContactController#postIndex')->name('contact.post');
Route::get('/profile/{user}', 'ProfileController#index')->name('profile'); //PROFILE
Route::get('/profile/{user}/follow', 'ProfileController#follow')->name('profile.follow'); //PROFILE
//LISTINGS
Route::group(['prefix' => 'listing'], function()
{
Route::get('/{listing}/{slug}', 'ListingController#index')->name('listing');
Route::get('/{listing}/{slug}/card', 'ListingController#card')->name('listing.card');
Route::get('/{listing}/{slug}/spotlight', 'ListingController#spotlight')->middleware('auth.ajax')->name('listing.spotlight');
Route::get('/{listing}/{slug}/verify', 'ListingController#verify')->middleware('auth.ajax')->name('listing.verify');
Route::get('/{listing}/{slug}/star', 'ListingController#star')->middleware('auth.ajax')->name('listing.star');
Route::get('/{listing}/{slug}/edit', 'ListingController#edit')->name('listing.edit');
#Route::get('/{listing}/{slug}/availability', 'AvailabilityController#availability')->name('listing.availability');
Route::any('/{id}/update', 'ListingController#update')->name('listing.update');
});
//ACCOUNT
Route::group(['middleware' => ['auth', 'isVerified'], 'prefix' => 'account', 'as' => 'account.', 'namespace' => 'Account'], function()
{
Route::get('/', function () {
return redirect(route('account.edit_profile.index'));
});
Route::resource('change_password', 'PasswordController');
Route::resource('edit_profile', 'ProfileController');
Route::resource('purchase-history', 'PurchaseHistoryController');
Route::resource('favorites', 'FavoritesController');
Route::resource('listings', 'ListingsController');
Route::resource('orders', 'OrdersController');
Route::get('payments/{id}/unlink', 'BankAccountController#unlink')->name('payments.unlink');
Route::resource('bank-account', 'BankAccountController');
Route::get('paypal/connect', 'PayPalController#connect')->name('paypal.connect');
Route::get('paypal/callback', 'PayPalController#callback')->name('paypal.callback');
});
//REQUIRES AUTHENTICATION
Route::group(['middleware' => ['auth', 'isVerified']], function () {
//INBOX
Route::resource('inbox', 'InboxController')->middleware('talk'); //Inbox
Route::get('/inbox/messages/{id}', 'InboxController#messages')->name('inbox.messages');
//CREATE LISTING
Route::resource('create', 'CreateController');
Route::any('/create/{listing}/session', 'CreateController#session')->name('create.session');
Route::get('/create/{listing}/images', 'CreateController#images')->name('create.images');
Route::get('/create/{listing}/additional', 'CreateController#additional')->name('create.additional');
Route::get('/create/{listing}/pricing', 'CreateController#pricing')->name('create.pricing');
Route::get('/create/{listing}/times', 'CreateController#getTimes')->name('create.times');
Route::post('/create/{listing}/times', 'CreateController#postTimes')->name('create.times');
Route::get('/create/{listing}/boost', 'CreateController#boost')->name('create.boost');
Route::post('/create/{listing}/uploads', 'CreateController#upload')->name('create.upload');
Route::delete('/create/{listing}/image/{uuid?}', 'CreateController#deleteUpload')->name('create.delete-image');
//CHECKOUT
Route::get('/checkout/error', 'CheckoutController#error_page')->name('checkout.error');
Route::get('/checkout/{listing}', 'CheckoutController#index')->name('checkout');
Route::post('/checkout/{listing}', 'CheckoutController#store')->name('checkout.store');
Route::get('/checkout/{session}/callback', 'CheckoutController#callback')->name('checkout.callback');
Route::any('/checkout/process/{listing}', 'CheckoutController#process')->name('checkout.process');
#Route::any('/checkout/test', 'CheckoutController#test')->name('checkout.test');
#Route::resource('stripe', 'StripeController');
#Route::any('/stripe/connect', 'StripeController#connect')->name('stripe.connect');
Route::any('/paypal/{listing}/start', 'PaypalController#start')->name('paypal.start');
Route::any('/paypal/cancel', 'PaypalController#cancel')->name('paypal.cancel');
Route::any('/paypal/callback', 'PaypalController#callback')->name('paypal.callback');
Route::any('/paypal/confirm', 'PaypalController#confirm')->name('paypal.confirm');
#Route::any('/paypal/create_agreement', 'PaypalController#create_agreement')->name('paypal.create_agreement');
});
//REQUIRES AUTHENTICATION
Route::group(['middleware' => ['auth']], function () {
Route::get('email-verification', 'Auth\EmailVerificationController#index')->name('email-verification.index');
Route::get('resend-verification', 'Auth\EmailVerificationController#resend')->name('email-verification.resend');
Route::get('email-verified', 'Auth\EmailVerificationController#verified')->name('email-verification.verified');
});
Route::get('login/facebook', 'Auth\LoginController#redirectToProvider');
Route::get('login/facebook/callback', 'Auth\LoginController#handleProviderCallback');
});
#errors
Route::get('/suspended',function(){
return 'Sorry something went wrong.';
})->name('error.suspended');
public function run(Listing $listing)
And you included a class in that namespace that matches Listing? Or is it available through service providers?
Remove parameter from function:
public function run();
and add the following line to the function:
$listing = func_get_arg(0);

Php parses function without create_function and without eval

I am trying to create a class to clean data for a brand before adding it to my database. As you can see I have added general filters (which can be used elsewhere). On the other hand, some fields will need a personalized cleaning. That's why I created 'function' in my array. My code is currently functional however the "create_function" function is deprecated and I would like to remove it but I cannot find an alternative without using "eval". Can you help me find a solution? Thank you.
<?php
class VehMarques
{
private static $fields_allowed = [
'_id' =>
[
'instanceof' => '\MongoDB\BSON\ObjectID',
],
'name' =>
[
'function' => 'if(!isset($name) && !isset($age)){return false;}',
],
'user' =>
[
'required',
'instanceof' => '\MongoDB\BSON\ObjectID',
],
'centre' =>
[
'required',
'instanceof' => '\MongoDB\BSON\ObjectID',
],
'time' =>
[
'instanceof' => 'MongoDB\BSON\UTCDateTime',
],
];
public static function add(array $fields)
{
$fields_options=array();
foreach(self::$fields_allowed as $key => $val)
{
foreach($val as $key1 => $val1)
{
if(in_array($val1, array('required')))
{
$fields_options[$val1][$key] = null;
}
else
{
$fields_options[$key1][$key] = $val1;
}
}
}
if(!empty(self::$fields_allowed) && !empty(array_diff_key($fields, self::$fields_allowed)))
{
return false;
}
if(!empty($fields_options['function']))
{
foreach($fields_options['function'] as $func)
{
$func = preg_replace('/\$([a-zA-Z0-9]+)/', '$fields[\'$1\']', $func);
if(create_function('$fields', $func)($fields) === false)
{
return false;
}
}
}
if(!empty($fields_options['required']) && !empty(array_diff_key($fields_options['required'], $fields)))
{
return false;
}
if(!empty($fields_options['instanceof']))
{
foreach($fields_options['instanceof'] as $key => $val)
{
if(!($fields[$key] instanceof $val))
{
return false;
}
}
}
if(!isset($fields['_id']))
{
$fields['_id'] = new \MongoDB\BSON\ObjectID();
}
if(!isset($fields['time']))
{
$fields['time'] = new MongoDB\BSON\UTCDateTime();
}
return true;
}
}
$insert_marque = array(
'_id' => new \MongoDB\BSON\ObjectID(),
'name' => 'Test',
'user' => new \MongoDB\BSON\ObjectID(),
'centre' => new \MongoDB\BSON\ObjectID(),
'time' => new MongoDB\BSON\UTCDateTime()
);
var_dump(VehMarques::add($insert_marque));
?>

How to add wishlist data to trailData without overwriting existing data?

I'm new to PHP and I'm building API for wishlist, for both guest users and logged-in users in Laravel Lumen. Here I'm using TrailManagerService as session manager
It saves data as
- for logged in users
Array
(
[trail_id] => 4b19bd9d-f2da-431b-8aba-d181d7eca736
[inception_time] => 1599813465
[last_used] => 1600762156
[customer_id] => 106210
[customer_data.customer_id] => 106210
[customer_data.firstname] => XXXX
[customer_data.lastname] => YYYY
[customer_data.gender] => Male
[customer_data.dob] => 1999-10-19
[customer_data.email] => xx#yy.com
[customer_data.mobile] => 2245436547
[customer_data.referral_code] => HRI11489
-for guest users
Array
(
[trail_id] => 8b7e6931-6ad3-48a0-af61-4caaab85cf20
[inception_time] => 1600761357
[last_used] => 1600761391
I want to add wishlist items to trailData and save it to DB if user does login and then emptytraildata after it get saved to DB. Also, if user doesnt login wishlist data should be saved in trailData for current session.
Code for WishlistControllerService
<?php
namespace App\Http\Services\v1\Products;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;
use App\Services\SOA\TrailManagerService;
use App\Repositories\WishlistRepository;
class WishlistControllerService
{
public function __construct(WishlistRepository $wishlistRepository)
{
$this->wishlistRepository = $wishlistRepository;
}
public function showList(Request $request){
$trailData = TrailManagerService::getAllTrailData('customer_id');
$trailCustomerId = TrailManagerService::getTrailData('customer_id');
$headerCustomerId = (int) $request->header('X-Customer-ID', 0);
$responseData = [];
$trailCustomerId = $trailData['customer_id'] ?? 0;
print_r($trailData);exit;
if($trailCustomerId === $headerCustomerId) {
// print_r("hi");exit;
$wishlistData = $this->wishlistRepository->getWishlist($trailCustomerId);
$responseData = [
'identifier' => 'wishlist',
'data' => [
'list' => $wishlistData
]
];
} else if($trailCustomerId === 0) {
// print_r("bye");exit;
// $tempWishlistItem = [
// // 'guestUserID' => $,
// 'productID' => $request->input('product_id'),
// 'sizeID' => $trailData['size_id'],
// 'productQuantity' => $request->input('quantity'),
// 'shippingPin' => $request->input('postal_code'),
// 'shippingCity' => $request->input('city_name'),
// ];
$responseData = [
'identifier' => '',
'data' => [
'list' => []
]
];
} else {
// print_r("why");exit;
$responseData = [
'status' => 403,
'message' => 'Access Forbidden'
];
}
return $responseData;
}
public function store($request, $productId){
$trailData = TrailManagerService::getAllTrailData();
$responseData = [];
$headerCustomerId = (int) $request->header('X-Customer-ID', 0);
$trailCustomerId = $trailData['customer_id'] ?? 0;
$tempWishlistItem =
[
// 'siteUserID`' => $customerId ?? $trailCustomerId,
'productID' => $productId,
'sizeID' => $request->input('size_id'),
'productQuantity' => $request->input('quantity'),
'currency' => strtoupper($request->input('currencyCode')),
];
$tempData[] =
array_push($trailData, $tempWishlistItem);
TrailManagerService::setTrailData($trailData);
print_r($trailData);exit;
// if($trailCustomerId === $customerId) {
$wId = $this->wishlistRepository->create($wishlistModelData);
$responseData = ['data' => ['userWID' => $wId]];
$wishlistModelData = [
'siteUserID' => $customerId,
'productID' => $productId,
'sizeID' => $request->input('size_id'),
'productQuantity' => $request->input('quantity'),
'currency' => strtoupper($request->input('currencyCode')),
];
// print_r($wishlistModelData);exit;
$wishlistItem = $this->wishlistRepository
->findWhere(['status' => 1, 'siteUserID' => $customerId, 'productID' =>
$productId]);
if(empty($wishlistItem[0]) === false) {
$responseData = [
'status' => 403,
'message' => 'Forbidden, Item already in Wishlist'
];
} else {
$wId = $this->wishlistRepository->create($wishlistModelData);
$responseData = ['data' => ['userWID' => $wId]];
}
} else {
// $tempWishlistData = [];
$tempWishlistItem =
[
// 'siteUserID' => $customerId ?? $trailCustomerId,
'productID' => $productId,
'sizeID' => $request->input('size_id'),
'productQuantity' => $request->input('quantity'),
'currency' => strtoupper($request->input('currencyCode')),
];
$tempWishlistData = array_merge($trailData, [$tempWishlistItem]);
print_r($tempWishlistData);exit;
$trailDataTemp = TrailManagerService::setTrailData(
$tempWishlistData
);
print_r($trailDataTemp);exit;
if($customerId === $trailData['customerID']){
foreach($tempWishlistData as $item) {
$wId = $this->wishlistRepository->create($wishlistModelData);
$responseData = ['data' => ['userWID' => $wId]];
}
TrailManagerService::emptyTrailData();
}
return $responseData;
}
I want to add wishlist items to trailData and save it to DB if user does login and then emptytraildata after it get saved to DB. Also, if user doesnt login wishlist data should be saved in trailData for current session.
Code for Wishlist Controller
<?php
namespace App\Http\Controllers\v1\Products;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Services\v1\Products\WishlistControllerService;
use Validator;
use App\Helpers\Utilities;
use App\Services\SOA\TrailManagerService;
use Illuminate\Support\Facades\Route;
class WishlistController extends Controller
{
private $controllerService;
public function __construct(WishlistControllerService $controllerService)
{
// $request = app(Request::class);
// $customerId = $request->header('X-Customer-ID', 0);
// TrailManagerService::authorize($customerId);
$this->controllerService = $controllerService;
}
public function index(Request $request)
{
$responseData = $this->controllerService->showList($request);
$httpStatus = $responseData['status'] ?? 200;
return $this->response($responseData, $httpStatus);
}
public function store(Request $request, int $productId){
$requestParams = $request->all();
// $requestParams['productId'] = $request->header('product_id');
$validator = Validator::make($requestParams,
[
'product_id' => 'integer',
'size_id' => 'integer',
'quantity' => 'required|integer|digits_between:1,2',
'currencyCode' => 'required|string|in:INR,EUR,USD,AUD,CAD,SGD,HKD'
],
[
'product_id.integer'=> 'Parameter product_id is mandatory',
'size_id.integer' => 'Invalid value for parameter size_id',
],
);
if ($validator->fails()) {
$messages = $validator->errors();
$responseData = Utilities::requestValiationResponse($messages);
} else {
// print_r($productId);exit;
$responseData = $this->controllerService->store($request, $productId);
}
$httpStatus = $responseData['status'] ?? 200;
return $this->response($responseData, $httpStatus);
}
public function remove(Request $request, int $productId)
{
$responseData = $this->controllerService->remove($request, $productId);
$httpStatus = $responseData['status'] ?? 200;
return $this->response($responseData, $httpStatus);
}
}
Code for Wishlist Repo
<?php
namespace App\Repositories;
use Prettus\Repository\Eloquent\BaseRepository;
use App\Models\MxUserWishlist;
use Illuminate\Support\Facades\DB;
use App\Helpers\Utilities;
class WishlistRepository extends BaseRepository
{
/**
* Specify Model class name
*
* #return string
*/
public function model()
{
return MxUserWishlist::class;
}
/**
* #param int $customerId
* #return array
*/
public function getWishlist($trailCustomerId): array
{
$wishlistData = [];
$query = "SELECT W.userWID, W.siteUserID, W.productID,P.productTitle, PSI.imageName,
W.sizeID, S.sizeTitle, D.designerName,P.designerID, P.categoryID,
PS.productPrice, PS.discountPercent,PS.filterPrice,P.seoUri
FROM mx_user_wishlist W
INNER JOIN mx_product P ON P.productID = W.productID
INNER JOIN mx_product_set PS ON (W.productID = PS.productID AND W.sizeID = PS.sizeID)
INNER JOIN mx_product_set_images PSI ON PSI.productID = W.productID
INNER JOIN mx_size S ON S.sizeID = W.sizeID
INNER JOIN mx_designer D ON P.designerID = D.designerID
WHERE W.siteUserID = $trailCustomerId";
$wishlistCollection = DB::select($query, ['siteUserID' => $trailCustomerId]);
if(empty($wishlistCollection) === false) {
foreach ($wishlistCollection as $key => $wishlist) {
$productId = 0;
$productUrl = '';
$productUrl = '/products/'.$wishlist->seoUri.'/'.$wishlist->productID;
$wishlistItems = [
'id' => $wishlist->productID,
'name' => $wishlist->productTitle,
'image' => config('global.cdni_url').'/tr:w-317/uploads/product/'.$wishlist->imageName,
'product_url' => $productUrl,
'sizes' => [
'id' => $wishlist->productID,
'name' => $wishlist->sizeTitle
],
'designer_name' => $wishlist->designerName,
'category_id' => $wishlist->categoryID,
'mrp' => $wishlist->productPrice,
'discount_percentage' => $wishlist->discountPercent,
'you_pay' => $wishlist->filterPrice,
];
}
return $wishlistItems;
} else {
$responseData = [];
return $responseData;
}
// return $responseData;
}

Non static method 'load' should not be called statically

this is the function, the error is in line 25 in
'$data = Excel::load($path)->get();' saying that None-Static méthode 'load' should not be called statically:
function import(Request $request)
{
$this->validate($request, [
'select_file' => 'required|mimes:xls,xlsx'
]);
$path = $request->file('select_file')->getRealPath();
$data = Excel::load($path)->get();
if($data->count() > 0)
{
foreach($data->toArray() as $key => $value)
{
foreach($value as $row)
{
$insert_data[] = array(
'zi' => $row['zi'],
'siteId' => $row['siteId'],
'gsmId' => $row['gsmId'],
'topoCont' => $row['topoCont'],
'plannRedr' => $row['plannRedr'],
'Country' => $row['country'],
'dateReal' => $row['dateReal'],
'semReal' => $row['semReal'],
'statuts' => $row['country'],
);
}
}
if(!empty($insert_data))
{
DB::table('tbl_customer')->insert($insert_data);
}
}
return back()->with('success', 'Excel Data Imported successfully.');
}
}
add this in your controller :
use Maatwebsite\Excel\Facades\Excel;

Categories