Mikrotik online users id is difference than normal user id - mikrotik

When i try to log mikrotik users activity we understood mikrotik assign another id to online users than when we created user with /ip/hotspot/user/add command, is there any solution to find which user connected to internet in mikrotik?
class MikrotikLoggerListener extends Command
{
protected $signature = 'mikrotik:logger';
protected $description = 'Mikrotik logger listener';
public function handle()
{
$users = User::all();
foreach ($users as $user) {
if ($user->log == 1) {
try {
$addRequest = new RouterOS\Request('/log print');
$result = (new RouterOS\Client($user->mikrotik_ip, $user->mikrotik_user, $user->mikrotik_password))->sendSync($addRequest);
foreach ($result as $object) {
$id = $object->getProperty('.id');
$time = $object->getProperty('time');
$topics = $object->getProperty('topics');
$message = $object->getProperty('message');
$exists = LogTemp::where('time','=',$time)->first();
if(!$exists) {
if (str_contains($message, 'logged out') || str_contains($message, 'disconnected')) {
$status = 'logged out';
$log = new LogTemp;
$log->user_id = $user->id;
$log->mikrotik_id = $id;
$log->time = $time;
$log->topics = $topics;
$log->message = $message;
$log->status = $status;
$log->save();
}
}
}
//--------------------------------------------------------------------------------------------------
$request = new RouterOS\Request('/ip/hotspot/active/print');
$router = new RouterOS\Client($user->mikrotik_ip, $user->mikrotik_user, $user->mikrotik_password);
$onlineUsers = $router->sendSync($request);
$count = $onlineUsers->count();
$this->info('customer: ' . $user->id . ' count: ' . $count);
for ($i = 0; $i < $count; $i++) {
if ($onlineUsers[$i]->getProperty('.id') != null) {
$mikrotik_id = $onlineUsers[$i]->getProperty('.id');
$current_user = LogTemp::where('user', '=', $onlineUsers[$i]->getProperty('user'))->first();
if ($current_user) {
$log = new LogTemp;
$log->user_id = $user->id;
$log->mikrotik_id = $mikrotik_id;
$log->user = $onlineUsers[$i]->getProperty('user') ?? '';
$log->address = $onlineUsers[$i]->getProperty('address') ?? '';
$log->mac_address = $onlineUsers[$i]->getProperty('mac-address') ?? '';
$log->login_by = $onlineUsers[$i]->getProperty('login-by') ?? '';
$log->bytes_in = $onlineUsers[$i]->getProperty('bytes-in') ?? '';
$log->bytes_out = $onlineUsers[$i]->getProperty('bytes-out') ?? '';
$log->packets_in = $onlineUsers[$i]->getProperty('packets-in') ?? '';
$log->packets_out = $onlineUsers[$i]->getProperty('packets-out') ?? '';
$log->status = 'online';
$log->save();
} else {
$log = new LogTemp();
$log->user_id = $user->id;
$log->mikrotik_id = $mikrotik_id;
$log->user = $onlineUsers[$i]->getProperty('user') ?? '';
$log->address = $onlineUsers[$i]->getProperty('address') ?? '';
$log->mac_address = $onlineUsers[$i]->getProperty('mac-address') ?? '';
$log->login_by = $onlineUsers[$i]->getProperty('login-by') ?? '';
$log->bytes_in = $onlineUsers[$i]->getProperty('bytes-in') ?? '';
$log->bytes_out = $onlineUsers[$i]->getProperty('bytes-out') ?? '';
$log->packets_in = $onlineUsers[$i]->getProperty('packets-in') ?? '';
$log->packets_out = $onlineUsers[$i]->getProperty('packets-out') ?? '';
$log->status = 'logged-in';
$log->save();
}
}
}
} catch (Exception $ignore) {
$this->info(' ->' . $ignore->getMessage());
}
try {
$addRequest = new RouterOS\Request('/log print');
$result = (new RouterOS\Client($user->mikrotik_ip, $user->mikrotik_user, $user->mikrotik_password))->sendSync($addRequest);
foreach ($result as $object) {
$message = $object->getProperty('message');
$mikrotik_id = $object->getProperty('.id');
if (str_contains($message, 'logged out') || str_contains($message, 'disconnected')) {
$current_user = LogTemp::where('user', '=', $mikrotik_id)->orderBy('id', 'DESC')->first();
if ($current_user) {
//dd($current_user);
$result = LogTemp::with('user')
->select([DB::raw('SUM(bytes_in) as download , SUM(bytes_out) as upload')])
->where('mikrotik_id','=',$mikrotik_id)
->groupBy('mikrotik_id')
->get();
$new_log = new UserConnectionsLog();
$new_log->user_id = $current_user->id;
$new_log->mikrotik_id = $current_user->mikrotik_id;
$new_log->user = $current_user->user;
$new_log->address = $current_user->address;
$new_log->mac_address = $current_user->mac_address;
$new_log->login_by = $current_user->login_by;
$new_log->bytes_in = $result['download'];
$new_log->bytes_out = $result['upload'];
$new_log->logged_in = $current_user->logged_in;
$new_log->logged_out = now();
//$new_log->save();
//LogTemp::where('mikrotik_id', '', $log->user)->delete();
}
}
}
} catch (Exception $ignore) {
$this->info('Log section error ->' . $ignore->getMessage());
}
}
}
}
}

Related

I need to convert full name in to a name with initials in laravel Ex: Simmon Alexander Hales to S.A. Hales

$names=Player::pluck('fullname');
$initials=[];
foreach($names as $name) {
$nameParts = explode(' ', trim($name));
$firstName = array_shift($nameParts);
$lastName = array_pop($nameParts);
$initials[$name] = (
mb_substr($firstName,0,1) .
mb_substr($lastName,0,1)
);
}
$names = Player::pluck('fullname');
$initials = [];
foreach ($names as $name) {
$initials[$name] = trim(collect(explode(' ', $name))->map(function ($segment) {
return mb_substr($segment, 0, 1);
})->join('.'));
}
print_r($initials);
Update:
$names = Player::pluck('fullname');
$initials = [];
foreach ($names as $name) {
$initials[$name] = trim(collect(explode(' ', $name))->reverse()->values()->map(function ($item, $key) {
if ($key == 0) {
return ' ' . $item;
} else {
return mb_substr($item, 0, 1);
}
})->reverse()->join('.'));
}
print_r($initials);

How to use save() method inside a loop in laravel

My current situation is: I must use save() method to save multiple records using loop. I know insert() will fix my problem but to maintain my code clean I have to use the same code and save() method to insert the record. I create new instance inside the loop but always only last record is being inserted. My code looks like:
public static function save($data)
{
$settings = Settings::instance();
$data['sender_address'] = urldecode($data['sender_address']);
$data['sender_address'] = json_decode($data['sender_address'], true);
extract($data);
$customerFields = ['name', 'mobile', 'alt_mobile', 'district_id', 'area_id', 'address'];
$customerObj = $customer = Customer::where('mobile', $mobile);
if ($customerObj->count()) {
$customer = $customer->first();
} else {
$customer = new Customer;
}
foreach ($customerFields as $customerField) {
if (!empty($$customerField)) {
$customer->$customerField = $$customerField;
}
}
($customerObj->count()) ? $customer->update() : $customer->save();
$order = (isset($order_id) && !empty($order_id) )? Order::find($order_id) : new Order;
$order->sender_address = $sender_address;
$order->branch_id = self::getBranchIdByAreaId($sender_address['area']);
$order->responsible_by = self::getBranchManagerIdByBranchId($order->branch_id);
$order->client_id = $client_id;
$order->customer_id = $customer->id;
$order->delivery_time = $delivery_time;
$deliveryChargeParams = [
'district_id' => $district_id,
'delivery_time' => $delivery_time,
'product_weight' => $product_weight,
'merchant_id' => $client_id,
];
$order->delivery_charge = Utility::getDeliveryCharge($deliveryChargeParams);
$order->vat = Utility::getVat($order->delivery_charge);
if (empty($order_id)) {
$order->status_id = ($role_id == Employee::CLIENT) ?
$settings['tracking']['default_status'] : Order::PACKAGINGDONE;
if (($role_id != Employee::CLIENT)) {
$order->requested = Order::PACKAGINGDONE;
}
}
$order->cash_amount = $cash_amount;
$order->cod_charge = Utility::getCodCharge($cash_amount);
$order->product_weight = $product_weight;
$order->client_reference = $client_reference;
if (empty($order_id)) {
$order->save();
$loggedInUserId = isset($data['fromApp'])?
$data['client_id'] : Auth::getUser()->id;
$order->number = self::orderNumber($order,$loggedInUserId);
$order->update();
} else {
$order->update();
}
if (($role_id != Employee::CLIENT)) {
self::updateDeliveryWithin($order);
}
PaymentAction::update($order);
}
The following method calls this save() method:
function onSave(){
$data = post();
$client_id = (Auth::getUser()->role_id == Employee::CLIENT) ? Auth::getUser()->id : $data['client_id'];
$sender_address = $data['sender_address'];
$file = Input::file('bulk_order');
$filename = time().'-'.rand(2000,99999999).'-'.$file->getClientOriginalName();
$result = $file->move('tempFiles',$filename);
$uploadedFilePath = 'tempFiles/'.$filename;
$contents = $this->csvToArray($uploadedFilePath);
// dd($contents); //exit;
unlink($uploadedFilePath);
$keys = array();
if(count($contents)){
$keys = array_keys($contents[0]);
}else{
throw new ApplicationException('Your Csv file is not in proper Format OR Empty!');
}
$fields = array('client_reference','customer_mobile','customer_alternative_mobile','customer_name','customer_district','customer_area','customer_address','product_weight_in_kg','delivery_time_in_hour','cash_collection');
$diff = array_diff($keys,$fields);
//dd($diff); exit;
if(count($diff)!=0){
throw new ApplicationException('Your Csv file is not in proper Format');
}
// dd($contents); exit;
foreach($contents as $row){
$data['name'] = $row['customer_name'];
$data['mobile'] = $row['customer_mobile'];
if(strlen($data['mobile']) == 10 ){
$data['mobile'] = '0'.$data['mobile'];
}
$data['alt_mobile'] = $row['customer_alternative_mobile'];
if(strlen($data['alt_mobile']) == 10 ){
$data['alt_mobile'] = '0'.$data['alt_mobile'];
}
$data['district_id'] = Utility::getDistrictIdByName($row['customer_district']);
$data['area_id'] = Utility::getAreaIdByName($row['customer_area']);
$data['address'] = $row['customer_address'];
$data['delivery_time'] = $row['delivery_time_in_hour'];
$data['product_weight'] = $row['product_weight_in_kg'];
$data['client_id'] = $client_id;
$data['sender_address'] = $sender_address;
$data['cash_amount'] = $row['cash_collection'];
$data['client_reference'] = $row['client_reference'];
$data['role_id'] = Auth::getUser()->role_id;
OrderAction::save($data);
}
\Flash::success('Bulk Order uploaded Successfully');
return Redirect::to('dashboard/shipments');
}
Is it possible to save multiple records with my approach? Thanks in advance.

I get this error when trying to verify the email of candidates, Array to String conversion

I have a laravel system that when someone registers, they get a link on their emails where they have to click on it to verify their email. Once they click the link, their information is stored in the users table and the candidates table.
However, values are only inserted in the users table and not the candidates table, and I get the error "Array to string conversion".
Also, the link works well in local host but not after hosting the system.
RegisiterController.php
Str.php`
public function registerCandidate(Request $request){
if(setting('general_enable_candidate_registration')!=1){
return abort(401);
}
$rules = [
'first_name'=>'required',
'last_name'=>'required',
'national_id'=>'required',
'gender'=>'required',
'email'=>'required|email|string|max:255|unique:users',
'date_of_birth_year'=>'required',
'date_of_birth_month'=>'required',
'date_of_birth_day'=>'required',
'categories'=>'required',
'picture' => 'nullable|max:'.config('app.upload_size').'|mimes:jpeg,png,gif',
'cv_path' => 'nullable|max:'.config('app.upload_size').'|mimes:'.config('app.upload_files'),
];
if(setting('general_candidate_captcha')==1){
$rules['captcha'] = 'required|captcha';
}
foreach(CandidateFieldGroup::where('registration',1)->orderBy('sort_order')->get() as $group){
foreach($group->candidateFields as $field){
if($field->type=='file'){
$required = '';
if($field->required==1){
$required = 'required|';
}
$rules['field_'.$field->id] = 'nullable|'.$required.'max:'.config('app.upload_size').'|mimes:'.config('app.upload_files');
}
elseif($field->required==1){
$rules['field_'.$field->id] = 'required';
}
}
}
$this->validate($request,$rules);
$requestData = $request->all();
$password= $request->password;
$requestData['name']= $request->first_name.' '.$request->last_name;
$requestData['display_name'] = $request->first_name;
$requestData['password'] = Hash::make($password);
$requestData['role_id'] = 3;
$fields = CandidateField::get();
//check if email verification is required
if(setting('general_candidate_verification')==1){
do{
$hash = Str::random(30);
}while(PendingUser::where('hash',$hash)->first());
$formData = $_POST;
$formData['name'] = $request->first_name.' '.$request->last_name;
$formData['display_name'] = $request->first_name;
$formData['role_id'] = 3;
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(PENDING_USER_FILES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$formData['picture'] = $file;
}
else{
$formData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = uniqid().'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$formData['cv_path'] = $file;
}
else{
$formData['cv_path'] =null;
}
$pendingUser = PendingUser::create([
'role_id'=>3,
'data'=> serialize($formData),
'hash'=> $hash
]);
//scan for files
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]) && $field->type=='file' && $request->hasFile('field_'.$field->id))
{
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
//dd($name);
$extension = $request->{'field_'.$field->id}->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $pendingUser->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(PENDING_USER_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$pendingUser->pendingUserFiles()->create([
'file_name'=>$_FILES['field_'.$field->id]['name'],
'file_path'=>$file,
'field_id'=>$field->id
]);
}
}
//send email to user
$link = route('confirm.candidate',['hash'=>$hash]);
$this->sendEmail($request->email,__('site.confirm-your-email'),__('site.confirm-email-mail',['link'=>$link]));
return redirect()->route('register.confirm');
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $request->date_of_birth_year.'-'.$request->date_of_birth_month.'-'.$request->date_of_birth_day;
$requestData['date_of_birth'] = $dateOfBirth;
//checkfor picture
if($request->hasFile('picture')) {
$path = $request->file('picture')->store(CANDIDATES,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$img = Image::make($file);
$img->resize(500, null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
$img->save($file);
$requestData['picture'] = $file;
}
else{
$requestData['picture'] =null;
}
if($request->hasFile('cv_path')) {
//$path = $request->file('cv_path')->store(CANDIDATES,'public_uploads');
$name = $_FILES['cv_path']['name'];
$extension = $request->cv_path->extension();
// dd($extension);
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('cv_path')->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$requestData['cv_path'] = $file;
}
else{
$requestData['cv_path'] =null;
}
$user->candidate()->create($requestData);
//save categories
$user->candidate->categories()->attach($request->categories);
//now save custom fields
$customValues = [];
//attach custom values
foreach($fields as $field){
if(isset($requestData['field_'.$field->id]))
{
if($field->type=='file'){
if($request->hasFile('field_'.$field->id)){
//generate name for file
$name = $_FILES['field_'.$field->id]['name'];
$extension = $request->{'field_'.$field->id}->extension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$path = $request->file('field_'.$field->id)->storeAs(CANDIDATE_FILES,$name,'public_uploads');
$file = UPLOAD_PATH.'/'.$path;
$customValues[$field->id] = ['value'=>$file];
}
}
else{
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
}
$user->candidateFields()->sync($customValues);
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
public function confirmCandidate($hash){
//get pending user
$pendingUser = PendingUser::where('hash',$hash)->first();
if(!$pendingUser){
abort(404);
}
$requestData = unserialize($pendingUser->data);
$password = $requestData['password'];
$requestData['password'] = Hash::make($password);
//check for profile picture and move to new directory
if(!empty($requestData['picture']) && file_exists($requestData['picture'])){
$file = basename($requestData['picture']);
$newPath = UPLOAD_PATH.'/'.CANDIDATES.'/'.$file;
rename($requestData['picture'],$newPath);
$requestData['picture'] = $newPath;
}
if(!empty($requestData['cv_path']) && file_exists($requestData['cv_path'])){
$file = basename($requestData['cv_path']);
$newPath = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$file;
rename($requestData['cv_path'],$newPath);
$requestData['cv_path'] = $newPath;
}
//First create user
$user= User::create($requestData);
//Calculate date of birth
$dateOfBirth = $requestData['date_of_birth_year'].'-'.$requestData['date_of_birth_month'].'-'.$requestData['date_of_birth_day'];
$requestData['date_of_birth'] = $dateOfBirth;
$user->candidate()->create($requestData);
//save categories
if(isset($requestData['categories'])){
$user->candidate->categories()->attach($requestData['categories']);
}
$fields = CandidateField::get();
$customValues = [];
//attach custom values
foreach($fields as $field){
if($field->type=='file'){
$pendingFile = $pendingUser->pendingUserFiles()->where('field_id',$field->id)->first();
if($pendingFile){
//generate name for file
$name = $pendingFile->file_name;
$info = new \SplFileInfo($name);
$extension = $info->getExtension();
$name = str_ireplace('.'.$extension,'',$name);
$name = $user->id.'_'.time().'_'.safeUrl($name).'.'.$extension;
$file = UPLOAD_PATH.'/'.CANDIDATE_FILES.'/'.$name;
rename($pendingFile->file_path,$file);
$customValues[$field->id] = ['value'=>$file];
}
}
elseif(isset($requestData['field_'.$field->id])){
$customValues[$field->id] = ['value'=>$requestData['field_'.$field->id]];
}
}
$user->candidateFields()->sync($customValues);
$pendingUser->delete();
$message = __('mails.new-account',[
'siteName'=>setting('general_site_name'),
'email'=>$requestData['email'],
'password'=>$password,
'link'=> url('/login')
]);
$subject = __('mails.new-account-subj',[
'siteName'=>setting('general_site_name')
]);
$this->sendEmail($requestData['email'],$subject,$message);
//now login user
Auth::login($user, true);
//redirect to relevant page
if(session()->exists('candidate_destination')){
$url = session()->get('candidate_destination');
session()->remove('candidate_destination');
return redirect($url);
}
else{
return redirect()->route('home');
}
}
`

Multiple where conditions in Laravel 5.1

i have a problem in my multiple filters implementation. I have some checkboxes that pass to AJAX some params that can have multiple values.
In my controller i have written this to handle this params:
function getCategoria(Request $request) {
$path_info = Request::getPathInfo();
$path = substr($path_info, 1);
$links = explode('/', $path);
$categorie = \App\Models\Categorie::where('primaria',1)->get();
$categoria = \App\Models\Categorie::where('link_statico', $path)->first();
$categoriaz = \App\Models\Categorie::where('link_statico', $path)->first();
$id = ucfirst($links[0]);
$prodottip = \App\Models\Prdotticategorie::where('prodotti2categorie.id_categoria', $categoriaz->id)->join('prodotti', 'prodotti.id', '=', 'prodotti2categorie.id_prodotto')->query();
$brands = Input::get('brands');
$genere = Input::get('genere');
$stagione = Input::get('stagione');
$this->data['links'] = $links;
$this->data['categorie'] = $categorie;
$this->data['categoria'] = $categoria;
$this->data['categoriaz'] = $categoriaz;
$this->data['id'] = $id;
$this->data['pages'] = 'categorie.frontend';
if(count($brands) > 0 && count($genere) > 0 && count($stagione) > 0)
{
if(count($brands) > 0)
{
$brands_array = [];
if(is_array($brands) || is_object($brands))
{
foreach ($brands as $brand)
{
$brands_array[] = $brand;
}
$rst = $prodottip->whereIn('prodotti.id_produttore', $brands_array);
}
}
if(count($genere) > 0)
{
$genere_array = [];
if(is_array($genere) || is_object($genere))
{
foreach ($genere as $gen)
{
$genere_array[] = $gen;
}
$rst = $prodottip->whereIn('prodotti.genere', $genere_array);
}
}
if (count($stagione) > 0)
{
$stagione_array = [];
if(is_array($stagione) || is_object($stagione))
{
foreach ($stagione as $stag)
{
$stagione_array[] = $gen;
}
$rst = $prodottip->whereIn('prodotti.stagione', $stagione_array);
}
}
$prodottix = $rst->paginate(18);
} else {
$prodottix = $prodottip->paginate(18);
}
$this->data['prodottix'] = $prodottix;
if (Request::ajax()) {
$page = 'layouts.'.CNF_THEME.'.categorie_ajax';
$view = view($page, $this->data)->render();
return response()->json(['html'=>$view]);
}
$page = 'layouts.'.CNF_THEME.'.categorie';
return view($page, $this->data);
}
The problem is that AJAX reload correctly but the results remaining the same. I can bring it working only if i an elseif with different scenarios like this:
if(count($brands) > 0 && count($genere) > 0 && count($stagione) > 0)
//query with 3 where
elseif(count($brands) > 0 && count($genere) == 0 && count($stagione) == 0)
// query with 1 where
Hi have read something on DynamicScopes in Laravel, but i need more help thks
function getCategoria(Request $request)
{
$path_info = Request::getPathInfo();
$path = substr($path_info, 1);
$links = explode('/', $path);
$categorie = \App\Models\Categorie::where('primaria', 1)->get();
$categoria = \App\Models\Categorie::where('link_statico', $path)->first();
$categoriaz = \App\Models\Categorie::where('link_statico', $path)->first();
$id = ucfirst($links[0]);
$prodottip = \App\Models\Prdotticategorie::where('prodotti2categorie.id_categoria', $categoriaz->id)->join('prodotti', 'prodotti.id', '=', 'prodotti2categorie.id_prodotto')->query();
$brands = Input::get('brands');
$genere = Input::get('genere');
$stagione = Input::get('stagione');
$this->data['links'] = $links;
$this->data['categorie'] = $categorie;
$this->data['categoria'] = $categoria;
$this->data['categoriaz'] = $categoriaz;
$this->data['id'] = $id;
$this->data['pages'] = 'categorie.frontend';
$rst = null;
if (count($brands) > 0) {
$brands = is_object($brands) ? array($brands) : $brands;
$rst = $prodottip->whereIn('prodotti.id_produttore', $brands);
}
if (count($brands) > 0) {
$genere = is_object($genere) ? array($genere) : $genere;
$rst = $prodottip->whereIn('prodotti.genere', $genere);
}
if (count($stagione) > 0) {
$stagione = is_object($stagione) ? array($stagione) : $stagione;
$rst = $prodottip->whereIn('prodotti.stagione', $stagione);
}
if(null !== $rst) {
$prodottix = $rst->paginate(18);
} else {
$prodottix = $prodottip->paginate(18);
}
$this->data['prodottix'] = $prodottix;
if (Request::ajax()) {
$page = 'layouts.' . CNF_THEME . '.categorie_ajax';
$view = view($page, $this->data)->render();
return response()->json(['html' => $view]);
}
$page = 'layouts.' . CNF_THEME . '.categorie';
return view($page, $this->data);
}
Considering $brands,$genere,$stagione are array by
default. If it is object then then type casting to array and using in
the query.
Removed first if condition which is checking count
of all 3 arrays and then trying to build up a query.
Created new variable $rst which is having default value as null. In any condition is satisfied then it will assign the query object to $rst.
At last checking is $rst not equal to null and calling its paginate method.
Hope this will clears to you and solve your problem. If not,at least you will get an idea how you can re-factor your code :)
function getCategoria(Request $request) {
$path_info = Request::getPathInfo();
$path = substr($path_info, 1);
$links = explode('/', $path);
$categorie = \App\Models\Categorie::where('primaria',1)->get();
$categoria = \App\Models\Categorie::where('link_statico', $path)->first();
$categoriaz = \App\Models\Categorie::where('link_statico', $path)->first();
$id = ucfirst($links[0]);
$prodottip = \App\Models\Prdotticategorie::where('prodotti2categorie.id_categoria', $categoriaz->id)->join('prodotti', 'prodotti.id', '=', 'prodotti2categorie.id_prodotto')->query();
$brands = Input::get('brands');
$genere = Input::get('genere');
$stagione = Input::get('stagione');
$this->data['links'] = $links;
$this->data['categorie'] = $categorie;
$this->data['categoria'] = $categoria;
$this->data['categoriaz'] = $categoriaz;
$this->data['id'] = $id;
$this->data['pages'] = 'categorie.frontend';
if(count($brands) > 0 && count($genere) > 0 && count($stagione) > 0)
{
if(count($brands) > 0)
{
$brands_array = [];
if(is_array($brands) || is_object($brands))
{
foreach ($brands as $brand)
{
$brands_array[] = $brand;
}
$prodottip = $prodottip->whereIn('prodotti.id_produttore', $brands_array);
}
}
if(count($genere) > 0)
{
$genere_array = [];
if(is_array($genere) || is_object($genere))
{
foreach ($genere as $gen)
{
$genere_array[] = $gen;
}
$prodottip = $prodottip->whereIn('prodotti.genere', $genere_array);
}
}
if (count($stagione) > 0)
{
$stagione_array = [];
if(is_array($stagione) || is_object($stagione))
{
foreach ($stagione as $stag)
{
$stagione_array[] = $gen;
}
$prodottip = $prodottip->whereIn('prodotti.stagione', $stagione_array);
}
}
}
$prodottix = $prodottip->paginate(18);
$this->data['prodottix'] = $prodottix;
if (Request::ajax()) {
$page = 'layouts.'.CNF_THEME.'.categorie_ajax';
$view = view($page, $this->data)->render();
return response()->json(['html'=>$view]);
}
$page = 'layouts.'.CNF_THEME.'.categorie';
return view($page, $this->data);
}

Get the information you entered to ID

This file is the database ID information all the fields and went and came to a Blade, I want to an ID information entered in the same panel Blade I send my face.
class DataGrid extends DataSet
{
protected $fields = array();
/** #var Column[] */
public $columns = array();
public $headers = array();
public $rows = array();
public $output = "";
public $attributes = array("class" => "table");
public $checkbox_form = false;
protected $row_callable = array();
/**
* #param string $name
* #param string $label
* #param bool $orderby
*
* #return Column
*/
public function add($name, $label = null, $orderby = false)
{
$column = new Column($name, $label, $orderby);
$this->columns[$column->name] = $column;
if (!in_array($name,array("_edit"))) {
$this->headers[] = $label;
}
if ($orderby) {
$this->addOrderBy($column->orderby_field);
}
return $column;
}
//todo: like "field" for DataForm, should be nice to work with "cell" as instance and "row" as collection of cells
public function build($view = '')
{
($view == '') and $view = 'rapyd::datagrid';
parent::build();
Persistence::save();
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
$cell = new Cell($column->name);
$sanitize = (count($column->filters) || $column->cell_callable) ? false : true;
$value = $this->getCellValue($column, $tablerow, $sanitize);
$cell->value($value);
$cell->parseFilters($column->filters);
if ($column->cell_callable) {
$callable = $column->cell_callable;
$cell->value($callable($cell->value, $tablerow));
}
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
$this->rows[] = $row;
}
$routeParamters = \Route::current()->parameters();
return \View::make($view, array('dg' => $this, 'buttons'=>$this->button_container, 'label'=>$this->label,
'current_entity' => $routeParamters['entity']));
}
public function buildCSV($file = '', $timestamp = '', $sanitize = true,$del = array())
{
$this->limit = null;
parent::build();
$segments = \Request::segments();
$filename = ($file != '') ? basename($file, '.csv') : end($segments);
$filename = preg_replace('/[^0-9a-z\._-]/i', '',$filename);
$filename .= ($timestamp != "") ? date($timestamp).".csv" : ".csv";
$save = (bool) strpos($file,"/");
//Delimiter
$delimiter = array();
$delimiter['delimiter'] = isset($del['delimiter']) ? $del['delimiter'] : ';';
$delimiter['enclosure'] = isset($del['enclosure']) ? $del['enclosure'] : '"';
$delimiter['line_ending'] = isset($del['line_ending']) ? $del['line_ending'] : "\n";
if ($save) {
$handle = fopen(public_path().'/'.dirname($file)."/".$filename, 'w');
} else {
$headers = array(
'Content-Type' => 'text/csv',
'Pragma'=>'no-cache',
'"Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Disposition' => 'attachment; filename="' . $filename.'"');
$handle = fopen('php://output', 'w');
ob_start();
}
fputs($handle, $delimiter['enclosure'].implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $this->headers) .$delimiter['enclosure'].$delimiter['line_ending']);
foreach ($this->data as $tablerow) {
$row = new Row($tablerow);
foreach ($this->columns as $column) {
if (in_array($column->name,array("_edit")))
continue;
$cell = new Cell($column->name);
$value = str_replace('"', '""',str_replace(PHP_EOL, '', strip_tags($this->getCellValue($column, $tablerow, $sanitize))));
$cell->value($value);
$row->add($cell);
}
if (count($this->row_callable)) {
foreach ($this->row_callable as $callable) {
$callable($row);
}
}
fputs($handle, $delimiter['enclosure'] . implode($delimiter['enclosure'].$delimiter['delimiter'].$delimiter['enclosure'], $row->toArray()) . $delimiter['enclosure'].$delimiter['line_ending']);
}
fclose($handle);
if ($save) {
//redirect, boolean or filename?
} else {
$output = ob_get_clean();
return \Response::make(rtrim($output, "\n"), 200, $headers);
}
}
protected function getCellValue($column, $tablerow, $sanitize = true)
{
//blade
if (strpos($column->name, '{{') !== false ||
strpos($column->name, '{!!') !== false) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = $this->parser->compileString($column->name, $array);
//eager loading smart syntax relation.field
} elseif (preg_match('#^[a-z0-9_-]+(?:\.[a-z0-9_-]+)+$#i',$column->name, $matches) && is_object($tablerow) ) {
//switch to blade and god bless eloquent
$_relation = '$'.trim(str_replace('.','->', $column->name));
$expression = '{{ isset('. $_relation .') ? ' . $_relation . ' : "" }}';
$fields = $tablerow->getAttributes();
$relations = $tablerow->getRelations();
$array = array_merge($fields, $relations) ;
$value = $this->parser->compileString($expression, $array);
//fieldname in a collection
} elseif (is_object($tablerow)) {
$value = #$tablerow->{$column->name};
if ($sanitize) {
$value = $this->sanitize($value);
}
//fieldname in an array
} elseif (is_array($tablerow) && isset($tablerow[$column->name])) {
$value = $tablerow[$column->name];
//none found, cell will have the column name
} else {
$value = $column->name;
}
//decorators, should be moved in another method
if ($column->link) {
if (is_object($tablerow) && method_exists($tablerow, "getAttributes")) {
$array = $tablerow->getAttributes();
$array['row'] = $tablerow;
} else {
$array = (array) $tablerow;
}
$value = ''.$value.'';
}
if (count($column->actions)>0) {
$key = ($column->key != '') ? $column->key : $this->key;
$keyvalue = #$tablerow->{$key};
$routeParamters = \Route::current()->parameters();
$value = \View::make('rapyd::datagrid.actions', array('uri' => $column->uri, 'id' => $keyvalue, 'actions' => $column->actions,
'current_entity' => $routeParamters['entity']));
}
return $value;
}
public function getGrid($view = '')
{
$this->output = $this->build($view)->render();
return $this->output;
}
public function __toString()
{
if ($this->output == "") {
//to avoid the error "toString() must not throw an exception"
//http://stackoverflow.com/questions/2429642/why-its-impossible-to-throw-exception-from-tostring/27307132#27307132
try {
$this->getGrid();
}
catch (\Exception $e) {
$previousHandler = set_exception_handler(function (){ });
restore_error_handler();
call_user_func($previousHandler, $e);
die;
}
}
return $this->output;
}
public function edit($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->add('_edit', $label)->actions($uri, explode('|', $actions))->key($key);
}
public function getColumn($column_name)
{
if (isset($this->columns[$column_name])) {
return $this->columns[$column_name];
}
}
public function addActions($uri, $label='Edit', $actions='show|modify|delete', $key = '')
{
return $this->edit($uri, $label, $actions, $key);
}
public function row(\Closure $callable)
{
$this->row_callable[] = $callable;
return $this;
}
protected function sanitize($string)
{
$result = nl2br(htmlspecialchars($string));
return Config::get('rapyd.sanitize.num_characters') > 0 ? str_limit($result, Config::get('rapyd.sanitize.num_characters')) : $result;
}
public function rowCount()
{
return count($this->rows);
}
}
This is the source of a rapyd-laravel widget/package, not a custom code.
According to DataGrid/DataSet documentation, you can use many sources:
https://github.com/zofe/rapyd-laravel/wiki/DataSet
DataSet/DataGrid are presenters, you can retrieve all data of your data source using
{{ $item->field }} or {{ $row->field }} respectively
See the docs please
https://github.com/zofe/rapyd-laravel/wiki

Resources