i have this code where the user uploaded image is saved.
is it possible in the meantime to create a thumbnail?
function saveImages($dataArray, $idArticles, $folderPath, $prefixFile){
$folderPathDefault = '../../media/articles/imm'.$idArticles.'/';
$prefixFileDefault = 'photo_';
if($folderPath == null){
$folderPath = $folderPathDefault;
array_map('unlink', array_filter((array) glob($folderPath."*")));
}
if($prefixFile == null){
$prefixFile = $prefixFileDefault;
}
if (!is_dir($folderPath)) {
// dir doesn't exist, make it
mkdir($folderPath);
}
$count = 1;
foreach ($dataArray as $data) {
$image_parts = explode(";base64,", $data);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . $prefixFile . $count . '.jpg';
file_put_contents($file, $image_base64);
$count ++;
}
}
Thank you
For those interested or solved with this function:
function resize_image($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
function saveImages($dataArray, $idArticles, $folderPath, $prefixFile){
$folderPathDefault = '../../media/articles/imm'.$idArticles.'/';
$prefixFileDefault = 'photo_';
if($folderPath == null){
$folderPath = $folderPathDefault;
array_map('unlink', array_filter((array) glob($folderPath."*")));
}
if($prefixFile == null){
$prefixFile = $prefixFileDefault;
}
if (!is_dir($folderPath)) {
// dir doesn't exist, make it
mkdir($folderPath);
}
$count = 1;
foreach ($dataArray as $data) {
$image_parts = explode(";base64,", $data);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$file = $folderPath . $prefixFile . $count . '.jpg';
file_put_contents($file, $image_base64);
$count ++;
}
if (!file_exists('../../media/articles/imm'.$idArticles.'/thumbnail/')) {
mkdir('../../media/articles/imm'.$idArticles.'/thumbnail/', 0777, true);
}
$dir = "../../media/articles/imm".$idArticles."/thumbnail/";
array_map('unlink', glob("{$dir}*.jpg"));
$immagine= "../../media/articles/imm".$idArticles."/";
$files = glob("$immagine*.*");
$uno= 1;
for ($i=0; $i<count($files); $i++) {
$image = $files[$i];
$url = $image;
$imgResize = resize_image($url, 360, 270);
$path = '../../media/articles/imm'.$idArticles.'/thumbnail/thumbnail_photo_'.$uno++.'.jpg';
imagejpeg($imgResize, $path);
}
}
Related
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());
}
}
}
}
}
$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);
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');
}
}
`
I am trying to upload animated gif as user avatar. These images are converted to base64 through javascript and then are uploaded using image intervention.
$img = Image::make(file_get_contents($file));
$mime = $img->mime();
if ($mime == 'image/jpeg')
$ext= '.jpg';
elseif ($mime == 'image/png')
$ext= '.png';
elseif ($mime == 'image/gif')
$ext= '.gif';
elseif($mime == 'image/x-icon')
$ext = '.ico';
elseif($mime == 'image/bmp')
$ext = '.bmp';
else {
$ext = '.jpg';
}
$name = time().$ext;
$path = public_path("images/$controller");
File::isDirectory($path) or File::makeDirectory($path);
if(property_exists($field, 'size') && !$ext=='.gif') {
$field->size = explode('*',$field->size);
if($img->resize($field->size[0], $field->size[1])->save("$path/$name")) {
$data[$key] = $name;
} else {
$data[$key] = null;
}
} else {
if($img->save("$path/$name")) {
$data[$key] = $name;
} else {
$data[$key] = null;
}
}
But, those images lose animation after upload. I don't know what to do. How to not lose animation?
Javascript code:
reader.onload = function(e) {
var src = e.target.result;
var name = file.name;
var type = file.type;
var img = "<img src='"+src+"' class='img-fluid mx-auto' alt='image'>";
$('.card_group_'+field+' .previewContainer_'+count+' .file-loading').remove();
$('.card_group_'+field+' .previewContainer_'+count+' .imagePreview').append(img);
$('.card_group_'+field+' .previewContainer_'+count+' .card-header').append(name);
var input = "input[name='"+field+"']";
var added = $(input).val();
if(added == '') {
$(input).val(src);
} else {
$(input).val(added+';'+src);
}
}
reader.readAsDataURL(file);
For now, you can use another function to save when it is a gif, and keep using others from the library.
if ($file->getClientOriginalExtension() == 'gif') {
copy($file->getRealPath(), $destination);
}
else {
$image->save($destination);
}
$width = $image->width();
$height = $image->height();
$image->destroy();
Credits to: https://github.com/Intervention/image/issues/176#issuecomment-58863939
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);
}