mercredi 28 décembre 2022

Insert has error when data column is double [closed]

Please help me

when i insert data to mysql has error

SQLSTATE[22007]: Invalid datetime format: 1366 Incorrect double value

But column in mysql I set double. I changed to int and float but same error.

I used laravel 5.5

thank you so much !

[[enter image description here](https://i.stack.imgur.com/8E9Qp.jpg)](https://i.stack.imgur.com/iSxoa.jpg)

i already change column price to int and float but same error



via Chebli Mohamed

Cannot use object of type stdClass as array (View: .../para-answers.blade.php)

<?php 
    $options = json_decode($question->answers); 
    $correct_answers = json_decode($question->correct_answers);
    
     $outer_index=0;

?>
<div class="row">
    <div class="col-md-12">
        <ul class="questions-container fullwidth">
          <?php 
          foreach($options as $option) { 
            // dd($user_answers);
            $cAnswer = $correct_answers[$outer_index]->answer;
            $uAnswer = $user_answers[$outer_index];
            // dd($uAnswer);
            // print_r($option->options[0]);
              $sub_options = (array)$option->options;
              $optionsl2  = null;
              // if(isset($option->optionsl2))
              // $optionsl2 = (array) $option->optionsl2; 


            foreach($sub_options as $key => $value)
             $sub_options = $value;
            ?>  
            <li>
                <div class="question">
                    <h3> <span class="language_l1">{!!$option->question !!}</span>
                     
                    </h3> </div>
               
                <div class="select-answer">
                    <ul class="row">
                    <?php $index=0; 
                     
                     foreach($sub_options as $key1 => $value1) { 
                        $correct_answer_class = '';
                        if($cAnswer==$index+1)
                        {
                              $correct_answer_class = 'correct-answer';
                        }
                        
                        $submitted_value = '';
                        if($user_answers) 
                        {
                           if($uAnswer == $index+1) 
                           {
                                $submitted_value = 'checked';
                                
                            }
                        }
                      
                        ?>
                        <li class="col-md-6  answer_radio" >
                            <input type="radio" name="option" id="1radio1"   disabled="">
                           
                        </li>
                        <?php $index++; } ?>
                    </ul>
                </div>
            </li>
            <hr>
            <?php } ?>

        </ul>
    </div>
</div>

Here we got an issue (Cannot use object of type stdClass as array). Please help me to solve this problem. In this we want to show result of students paragraph questions... This project build on laravel 5.2 please check the following errors solve this... I get this error while we take a paragraph exam.



via Chebli Mohamed

mardi 27 décembre 2022

How do I pass a method with my own constraints in a controller that uses request pattern to display data

Merry Christmass team! I have a problem trying to figure out how to pass a method with my own constraints in a controller that is bound to request patter paradigm:

Sample Controller Code:

class SampleController
{
    protected $model = SampleModel::class;
    protected $indexRequest = IndexRequest::class;
 
}

Request Class

class IndexRequest extends FormRequest
{

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */

    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [];
    }

Assume I have a method that I want to do something different.Say I want to fetch some data based on some column constraints. Whats the approach?



via Chebli Mohamed

dimanche 25 décembre 2022

Openwisk getting bad request error(400) while trying to create from Laravel App

Trying to create a openwisk action from laravel, with python zip file, but getting following error

PUT https://192.168.1.13:31001/api/v1/namespaces/_/actions/test_new_03?blocking=true&result=true&overwrite=false` resulted in a `400 Bad Request` response:
{"code":"H6PLPnMvnyTnzhNt6X8IQiAt8IDRAmLK","error":"The request content was malformed:\nUnexpected end-of-input at input (truncated...)

here is my header

'headers' => [
                'Authorization' => 'Basic <token>',
                'stream' => true,
                "Connection" => "keep-alive",
                "content-type" => "application/json"
            ]

using guzzle http.



via Chebli Mohamed

samedi 24 décembre 2022

Error 500 in laravel 5.2 when user was loged in

I was run composer update and composer selfupdate in laravel project now I get error 500 and blank white page after user login and see project pages this picture is my log

laravel log

I run this command

php artisan key:generate
php artisan cache:clear 
composer install
composer dump-autoload

anybody can help me?



via Chebli Mohamed

vendredi 23 décembre 2022

Data is not coming in laravel 5.4 after using timestamp in query

Data is not coming when comparing current time between 2 times to fetch data in Laravel. Both times are saved in the database as timestamp and in query also I am using timestamp. Below is the code i wrote:-

$current_date = strtotime(date('d-m-Y H:i:s'));
        
$bookings = MachineBooking::with('userDetail')->where('machine_id', $machine_id)->where('time_from', '>=', $current_date)->where('time_to', '<', $current_date)->get();

"time_from" and "time_to" both timestamps are saved in bigint format in database. I entered timestamp using search option in direct database also still data did not come. Can someone please tell me where i am making mistake.



via Chebli Mohamed

jeudi 22 décembre 2022

Laravel Eloqunet query on first relation of one to many

I have Two Tables A and B A can have more than B the relation between them is that B has A_id columns in B have A_id and date I have a filter with status (status alpha = first B of A date is less than 30 days,beta = first B of A date is less than 60) when trying to get the status I want to query on the first row in B which has A_id

public function alpha(){
    return $this->hasOne("App/B")->where('date','<',now()->subMonth(1)->toDateString())->where('date','>',now()->subMonth(2)->toDateString());
}
public function beta(){
    return $this->hasOne("App/B")->where('date','<',now()->subMonth(2)->toDateString());
}

This seems to get the job done but failed in specific situation imagine table B has two rows

  1. id = 1 A_id=1 and date is 45 days old
  2. id =2 A_id=1 and date is 70 days old

This should be an alpha since I'm only interested in the First date but the query I've written returns on both alpha and beta how can I fix my query to only check the first occurrence only mind that I can't loop over A's after getting them since I'm using pagination



via Chebli Mohamed

mardi 20 décembre 2022

is there any way to detect which extension is impacting my site? [closed]

My website is about education and has some online tests, but another party has made an extension to autofill answers according to the available question data, Is there any solution to prevent it?

Thanks all

I tried creating another extension to turn it off and force users to download my extension before accessing the site, but the other cheater faked another extension with the same name. and my pagkeid to still access the page



via Chebli Mohamed

Trying to get property of non-object

im getting "Trying to get property 'selleruserid' of non-object" this error. How can i resolve this error?

$selleruserid= 0;


$featured['items'] = Items::with('Ratings')->select('items.item_id', 'items.user_id AS selleruserid', 'items.item_liked','items.item_slug','items.item_preview','items.item_name','items.item_type','users.user_photo','users.username','users.user_document_verified','items.updated_item','items.item_sold','items.free_download','items.item_flash','items.item_type_cat_id','items.regular_price','items.item_token', 'items.mainpage_boost_last')->leftjoin('users', 'users.id', '=', 'items.user_id')->where('items.item_status','=',1)->where('items.mainpage_boost_last','>', $today_date)->where('items.drop_status','=','no')->orderBy(DB::raw('RAND()'))->take($setting['setting']->home_featured_items)->get();


$selleruserid = $featured->selleruserid; // ERROR LINE


$checkuser = Items::checkuser($selleruserid);

I will be glad if you help me thank you



via Chebli Mohamed

lundi 19 décembre 2022

The problem is that when selecting from select it has ware:model, the slider crashes, and when you click on search, it shows 404

When I use livewire The problem is that when selecting from select it has ware:model, the slider crashes, and when you click on search, it shows 404

As shown in the picturesenter image description here

I tried many times but I don't know why

//my view

div class="ne-sidebar sidebar-break-lg col-xl-4 col-lg-12 px-0">

            <div class="sidebar-box item-box-light-md">
              <div class="topic-border color-cinnabar mb-30">
                <div class="topic-box-lg color-cinnabar"> </div>
              </div>
              <div class="bodyimg">
                <form action="" method="post" name="dmarticlesFilter" id="dmarticlesFilter">
                    @csrf
            <div id="dmarticlesfilter_filters">
                <div class="dmarticlesfilter_filters_row">
                <select id="filterCategory634bd4c1cb9b5_0" wire:model="fcategory_id">
                            <option></option>
                            @foreach($firstcategories as $fcat)
                              <option value=""></option>
                            @endforeach
                    </select>



                    <select id="filterCategory634bd4c1cb9b5_1" wire:model="scategory_id">
                            <option></option>
                            @foreach($secondcategories as $scat)
                              <option value=""></option>
                            @endforeach
                    </select>


                        </div>

                        <div class="dmarticlesfilter_filters_values_l">
                            <input placeholder="Title" type="text" name="filterTitle" value="">

                    <span><input type="submit" class="button" id="button" value=""> </span>&nbsp;&nbsp;
                    <a > </a>
                  </div>
                    </div>

                </form>
                </a>
              </div>
            </div>


//my controller

<?php

class HomeComponent extends Component
{
    public $fcategory_id;
    public $scategory_id;
    public $tcategory_id;


    public function render()
    {


        /***************************** */
        $firstcategories = firstcategory::all();
        $secondcategories = secondcategory::where('fcategory_id',$this->fcategory_id)->get();
        $thirdcategories = thirdcategory::where('scategory_id',$this->scategory_id)->get();
        $fourthcategories = fourthcategory::where('tcategory_id',$this->tcategory_id)->get();


        return view('livewire.home-component',['fourthcategories'=>$fourthcategories,'thirdcategories'=>$thirdcategories,'secondcategories'=>$secondcategories,'firstcategories'=>$firstcategories])->layout('layouts.base');
    }
}

I think the problem is with livewire with wire:model



via Chebli Mohamed

dimanche 18 décembre 2022

Returned data from a Script shows select option behind Boostrap Modal on Laravel

I have a simple JavaScript that retrieves set of data from my database and returns the result on my blade page Bootstrap Modal, however, as I enter the keyword value to retrieve, the select option result appears behind the modal form. How can I show it in front or within the modal? I adjusted the height of the modal but still the same. enter image description here



via Chebli Mohamed

vendredi 16 décembre 2022

React + Laravel 5.6 api CORS issue [closed]

I tried all solutions that I could lay my hands and finally, this solution helped progressing 1 step. Laravel 5.6 CORS issue.

However, It is adding duplicate urls in Acess-Control-Allow-Origin' and throwing this error Access to XMLHttpRequest at 'https://test.domain.com/api/login' from origin 'https://test.domain.com' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'https://test.domain.com, https://test.domain.com', but only one is allowed. Any suggestion how to prevent it?



via Chebli Mohamed

jeudi 15 décembre 2022

Laravel web application is not connecting to mysql localhost but connecting to mysql command line client

I am working on a Laravel web application and trying to run the website on Mysql localhost but I can't able to do that and when I try to connect, it connects to the database present in Mysql command line client. Are they both mysql commad line client and mysql localhost are different or same.

and why the laravel application is connecting directly to mysql command line client

I have share laravel configuration file such as : 1).env 2)app.php 3)database.php

enter image description here enter image description here enter image description here

I try to connect the laravel application with xampp mysql localhost but it didn't connected.



via Chebli Mohamed

Laravel 5.8 Undefined index: app_name [closed]

Undefined index: app_name (View: C:\Users\Hp\Documents\Coding\project_konekthing\erp_rental\framework\resources\views\auth\login.blade.php)

I've only tried to clone from the git when I run it this error occur

What happened? and how to solve it?



via Chebli Mohamed

mardi 13 décembre 2022

syntax error, unexpected 'readonly' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)

enter image description here I'm trying to decode qr code form local storage but get following error syntax error, unexpected 'readonly' (T_STRING), expecting function (T_FUNCTION) or const (T_CONST)


namespace Crm\Http\Controllers;

use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Storage;
use Libern\QRCodeReader\QRCodeReader;

class ScanQrCodeController extends Controller
{

    // public function __construct(string $imagePath)
    // {
    //     $imagePath = $this->imgPath;
    // }
  
        public  function scanQrCode()
        {
            $qrCodeScan = new QRCodeReader();
            
            $data = Storage::exists('public/uploads/companies/1/1/AVL0CQ/testQR.png');
            $url  = Storage::url('public/uploads/companies/1/1/AVL0CQ/testQR.png');
            $imgPath = (string) 'storage/uploads/companies/1/1/AVL0CQ/testQR.png';
            $qrCodeData = $qrCodeScan->decode($imgPath);
             
            return [
                "qr file exists " => $data,
                "url " => $url,
                //  "qr code output"  => $qrCodeData
            ];

        }

}


via Chebli Mohamed

lundi 12 décembre 2022

Single Signin For All Subdomain Or Projects?

Hy All Hope All Are Fine. First Of All Sorry For My English And I Am Totally New And didn't Know About Php My Sql Etc, So Lets Start My Questions With Detail I Purchased too many Projects subdomain1.maindomain subdomain2.maindomain subdomain3.maindomain subdomain4.maindomain May Be In Future I Will Add More Now Simply I Want Single Login For All Subdomains, Mean That User Can Signup In One Of Any Domain But Can Login For All Subdomain As Same Signup For any One Of Above Domain. My Sql Database User Is Same But Mysql Database Is Different One From Other Every Subdomain or Domain Has It's Own Database. Please Tell Me Is It Possible To Login As A One???? Please If It Is Possible Share With Detail Because I Am New. I Did't Try Any Method



via Chebli Mohamed

dimanche 11 décembre 2022

What would be the proper steps to upgrade laravel version 5 to latest version 9

I have an old project which I developed in Laravel 5.3 and I want to upgrade the project to Laravel v9. What are the steps to upgrade?

What I have seen so far on the internet and from my knowledge:

Upgrade to each higher version step by step e.g 5.3 to 5.4 ... 6 to 7 to 8 to 9

I am running php 8 on my macos. And currently, my code is not running because of deprecated methods in php 5.6 that my Laravel 5.3 is using.

How to upgrade properly?

My composer.json file is

{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": ["framework", "laravel"],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.6.4",
        "laravel/framework": "5.3.*",
        "appzcoder/crud-generator": "^2.0",
        "laravelcollective/html": "5.3.*",
        "doctrine/dbal": "^2.5",
        "maatwebsite/excel": "~2.1.0",
        "predis/predis": "~1.0",
        "guzzlehttp/guzzle": "~4.0",
        "laravel/scout" : "^2.0",
        "algolia/algoliasearch-client-php": "^1.17",
        "fx3costa/laravelchartjs": "^2.2",
        "gloudemans/notify": "^1.0",
        "pda/pheanstalk": "~3.1"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~5.0",
        "symfony/css-selector": "3.1.*",
        "symfony/dom-crawler": "3.1.*"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-root-package-install": [
            "php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "php artisan key:generate"
        ],
        "post-install-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postInstall",
            "php artisan optimize"
        ],
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "php artisan optimize"
        ]
    },
    "config": {
        "preferred-install": "dist",
        "allow-plugins": {
            "kylekatarnls/update-helper": true
        }
    }
}



via Chebli Mohamed

vendredi 9 décembre 2022

Replacing Google OAuth API in Laravel

I have an app that I was tasked with to renew. However, the app runs a Google OAuth API to authenticate the users. However, this instance of the API no longer works as the company has changed name and thus the old mail domain no longer exists.

E.g: name@companyname.com

Is there a way for me to change the instance of the api so it will allow any gmail to get in.

here's my current controller for the oauth

public function checkUserByToken($social_token)
    {
        $client  = new \Google_Client(['client_id' => env('GOOGLE_CLIENT_ID', '')]);
        $payload = $client->verifyIdToken($social_token);
        if ($payload) {
            $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)oldcompany.com$/i',
            ]);
            if ($validator->fails()) {
                return false;
            }
            $user = User::where('email', $payload['email'])->first();
            if (!$user) {
                $data = [
                    'name'      => $payload['family_name'],
                    'full_name' => $payload['name'],
                    'email'     => $payload['email'],
                    'password'  => bcrypt(str_random(8)),
                ];
                $user = $this->createUser($data);
            }
            $user->forceFill([
                'email' => $payload['email'],
                'email_verified_at' => Carbon::now(),
            ])->save();
            $tokenResult = $user->createToken('Personal Access Client');
            $token = $tokenResult->token;
            $token->expires_at = Carbon::now()->addMonth();
            $token->save();
            $data = [
                    'access_token' => $tokenResult->accessToken,
                    'token_type'   => 'Bearer',
                    'expires_at'   => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString(),
                    'full_name'    => $payload['name'],
                    'avatar'       => $payload['picture'],
                    'role'         => $user->role,
                    'section'      => isset($user->section)?$user->section->name:"",
                    'id'           => $user->id
            ];
            return $data;
        } else {
            return false;
        }
    }

I have tried replacing the google OAuth API in .env and change

 $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)oldcompany.com$/i',
            ]);

to

 $validator = Validator::make($payload, [
                'email' => 'required|email|regex:/(.*)newcompany.com$/i',
            ]);

no avail as I think the google API outside of sending back auth token also send back something else but I'm not sure what it is.



via Chebli Mohamed

Controller does not exist in laravel 5.6

I have this error where it said that the controller does not exist

My routes

use App\Http\Controllers\PasienController;  
Route::resource('/pasien', PasienController::class)->only(['index']);

The controller

<?php

namespace App\Http\Controllers;

use App\Token;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Validator;
use RealRashid\SweetAlert\Facades\Alert;

class PasienController extends Controller
{
    public function index(Request $request)
    {
        $patient = null;
        if (isset($request->nik)) {
            $response = $this->patient_by_nik($request->nik);
            $data = $response->getData();
            if ($response->status() == 200) {
                if ($data->total) {
                    $patient = $data->entry[0]->resource;
                    Alert::success($response->statusText(), 'Pasien Ditemukan');
                } else {
                    Alert::error('Not Found', 'Pasien Tidak Ditemukan');
                }
            } else {
                Alert::error($response->statusText() . ' ' . $response->status());
            }
        }
        
}

I was trying to get data from an API and return the data



via Chebli Mohamed

mercredi 7 décembre 2022

The "--path" option does not exist

The "--path" option does not exist.

Artisan::call("migrate --path=database/migrations/tenant")

i updated Laravel from 5.8 to laravel 8

i don't know that wrong

Artisan::call("migrate") work fine



via Chebli Mohamed

page not opening when click the post

I am newbie in development please help,Do not judge me. Remember everyone starts from 0.

When I click my ticket it is not opening specific page while click link of my ticket it shows in link correct ticket id but page not opening "404 not found"

Ticket.blade.php

`

                        
                                <tr>
                                                                     
                                                                     
                                    @foreach ($ticketsinfos as $ticketinfo)
                                    <td>IR-173049</td>
                                    <td>Dito Katsarava</td> 
                                    <td></td>
                                    
                                    <td><a href="/tickets/show/"></a></td>
                                    
                                    <td><button class="btn btn-danger btn-sm" type="button">Action Needed<br></button><br></td>
                                    <td>Tako Kiknadze</td>
                                    <td></td>
                                    <td></td>
                                </tr>

                                @endforeach  
                              
                                </tr>

`

web.php

`

<?php

use App\Http\Controllers\AdminsUserController;
//use App\Http\Controllers\UserController;
//use App\Http\Controllers\CompaniesController;
use App\Http\Controllers\DashboardController;
use App\Http\Controllers\TicketsController;
//use App\Models\AdminsUser;
//use App\Models\Companies;
use Illuminate\Support\Facades\Route;

/*
|----------------------------------------------z----------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::resource('/dashboard', DashboardController::class);

Route::resource('/tickets', TicketsController::class);

Route::resource('/admin/users', AdminsUserController::class);
// Route::resource('/companies', CompaniesController::class);




Auth::routes();

Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');


`

Controller

`

  public function show(Tickets $tickets)
    {
        //
        $tickets = Companies::with('tickets')->get();

        $severities = Severities::with('severity')->get();
        
        $ticketsinfos = Tickets::with('companies')->findOrFail(2);
    
        

  
     return view('customer.index', compact($tickets))->with(['tickets' => $tickets])->with(['severities' => $severities])->with(['ticketsinfos' => $ticketsinfos]);

    //dd($ticketsinfos->toArray());
        
    }

`

When I 'dd' works

Thanks you.



via Chebli Mohamed

laravel Unique Validation on row where is_active is 1

I want to implement unique validation on one column but it should only check active rows of the table. so is there any way I can implement this logic using laravel validation?

Below is the logic I am using to check unique records but its not working.

unique:users,email,is_active,1


via Chebli Mohamed

mardi 6 décembre 2022

Laravel "Trying to access array offset on value of type null" error when trying to render markdown

I'm trying to show some changelog content on my Laravel page with this markdown plugin, but it always throws this error: Trying to access array offset on value of type null

@markdown($changelog->content)

The content is not null, all the content is there and it gets created and stored properly.

I found out about @isset but no matter how I use it, it still shows that error.

@isset($changelog->content)
  @markdown($changelog->content)
@endisset

Note: I'm using Laravel 5.8, this is an older project.



via Chebli Mohamed

lundi 5 décembre 2022

FatalThrowableError in Call to a member function get_one() on null

i have some laravel code like this

public function update_password(Request $request)
    {
        $data = array(
            'password_current' => $request->input('password_current'), 
            'password_new' => $request->input('password_new'),
            'password_new_confirmation' => $request->input('password_new_confirmation'), 
            );

        $rules = [
            'password_current' => 'required',
            'password_new' => 'required|confirmed',
            'password_new_confirmation' => 'required',
        ];

        $validator = Validator::make($data, $rules);
        if ($validator->fails()) {   
            return redirect()->action('Editor\ProfileController@edit_password')->withInput()->withErrors(['New password confirmation failed!']);
        } else {
            
            $user = $this->UserRepository->get_one(Auth::user()->id);
            
            if(Hash::check($request->input('password_current'), $user->password))
            {
                $this->UserRepository->change_password(Auth::user()->id, $request->input('password_new'));

                return redirect()->action('Editor\ProfileController@show');
            } else {
                return redirect()->action('Editor\ProfileController@edit_password')->withInput()->withErrors(['Current password mismatch!']);
            }
        }
    }

but when i run the program, the program notification is FatalThrowableError, Call to a member function get_one() on null. i change with other script in google but no one is work.

$user = $this->UserRepository->get_one(Auth::user()->id);

anyone ever had this problem?

I try to change script like

use Auth;
$user_id = Auth::user()->id;

and still not work.



via Chebli Mohamed

dimanche 4 décembre 2022

Need to replace a static value in all controllers even in whole project. Is there any way that i can change this value from only a single function?

I have a pre-build project and there is some static value passed in the whole project. Instead of looking in every controller and blade file, I want to change these static values replace to the values from the env file.

**What I tried: ** In the bootstrap folder in the app.php file, I created a function for replacing static values by using str_replace() and call this function in the same file. This is not working.

I don't want to change the static value in the controller, But on the run time.

<?php

/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/

$app = new Illuminate\Foundation\Application(
    $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);

/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/

$app->singleton(
    Illuminate\Contracts\Http\Kernel::class,
    App\Http\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Console\Kernel::class,
    App\Console\Kernel::class
);

$app->singleton(
    Illuminate\Contracts\Debug\ExceptionHandler::class,
    App\Exceptions\Handler::class
);

/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/


function replaceHello()
{
    str_replace("world","all.","Hello world");
}
replaceHello();

return $app;

This function is for replace world from the hello world to hello all in whole project. Is there any way to do this?



via Chebli Mohamed

samedi 3 décembre 2022

Lumen queue throwing MySQL server has gone away error

I'm calling a common function from Lumen queue and cron job. During user interaction this function is called from queue ( async purpose ), if something goes wrong with queue execution for example lock wait timeout etc. I have a cron job which is scheduled for every 15 mins to process older transactions. There is no issue when cron is executed but whenever queue is executed MySQL server has gone away error is occurring. Error is occurring at the line DB::connection()->getpdo()->exec('BEGIN');

I did some research on internet, those articles are saying this kind of error will raise when we try to insert large data and we can avoid this error my increasing max_allowed_packet. But error is occurring at beginning line itself, I'm not trying to insert large data ( mostly it should be in KBs ) and moreover same function is working when cron executes for every 15 mins. Following are my code snippets,

public function processTransaction($data)
{
    try {
        $this->validate($data);
        DB::connection()->getpdo()->exec('BEGIN');
    // Save & Update DB 
        DB::connection()->getpdo()->exec('COMMIT');
    } catch (Exception $ex) {
        DB::connection()->getpdo()->exec('ROLLBACK');
        Log::error($ex->getMessage() . '-' . $ex->getTraceAsString());
        throw new AppException($ex->getMessage(), $ex->getCode());
    }
}

Above is the initial version I tried, in this case error was at ROLLBACK statement. Later I had updated to following

public function processTransaction($data)
{
    try {
        $this->validate($data);
        DB::connection()->getpdo()->exec('BEGIN');
    // Save & Update DB 
        DB::connection()->getpdo()->exec('COMMIT');
    } catch (Exception $ex) {
        Log::error($ex->getMessage() . '-' . $ex->getTraceAsString());
        try {
            DB::connection()->getpdo()->exec('ROLLBACK');
        } catch (Exception $ex) {
            Log::error($ex->getMessage() . '-' . $ex->getTraceAsString());
        }
        throw new AppException($ex->getMessage(), $ex->getCode());
    }
}

Here the error is at BEGIN statement and PDO exception error code is in string, which is also creating the issue for argument 2 AppException (extends Exception class), which excepts argument 2 as integer. I think PDO exception issue can be handled by separately catching PDO exception but I want to know why MySQL server has gone error is getting.



via Chebli Mohamed

vendredi 2 décembre 2022

How can i use redirect()->route('test', $id) after create a data in Laravel? [closed]

The store function

The Route

I try to store a data to database and than i want to redirect the page with the created data ID. I use return redirect()->route('test', $id) but its not working.



via Chebli Mohamed

how can I handle errors in laravel mail

Laravel app sending mails with mandrillapp and Mailchimp. it's working.

How do you handling errors? How can I know is the mail sent or not?

Mail is send with Mail::sent() in try/catch block.

count(Mail::failures) is always 0. I can't find what type or error is needed to show in failures[]?

I can catch

Swift_RfcComplianceException

and

Swift_TransportException

I read the mailchimp documentation but can't find some return of API which says about mail status.

Any idea or suggestion about error handling?



via Chebli Mohamed

jeudi 1 décembre 2022

How to get the result with these time intervals in php

I'm using a time clock system which, by default, records only the employee's entry and exit times. I'm customizing it so that it's possible to also record break times but I'm having trouble getting the break time to be subtracted from the total time. This snippet of code is used to register the time between the check-in and check-out:

$time1 = Carbon::createFromFormat("Y-m-d H:i:s", $timeIN); 
$time2 = Carbon::createFromFormat("Y-m-d H:i:s", $timeOUT); 
$th = $time1->diffInHours($time2);
$tm = floor(($time1->diffInMinutes($time2) - (60 * $th)));
$totalhour = ($th.".".$tm);

The variable ($totalhour) receives the total value between the input register and the output register. It sends to the database in H.i format (hour.minutes), then another page searches for this information in the database and replaces the point (.) with (hr). Based on this code, I did the same to get the interval start and end timestamps. I was able to get the time between the start time and end time interval with the code below:

$breakstart = table::attendance()->where([['idno', $idno]])->value('breakstart');
$breakend = table::attendance()->where([['idno', $idno]])->value('breakend');
$one = Carbon::createFromFormat("H:i:s", $breakstart); 
$two = Carbon::createFromFormat("H:i:s", $breakend);
$breakone = $one->diffInHours($two);
$breaktwo = floor(($one->diffInMinutes($two) - (60 * $breakone)));
$totalbreak = $breakone.".".$breaktwo;

The $totalbreak variable stores the time taken between the start and end of the break. I was also successful in getting the time between this interval. Now, I need the total time to be done by subtracting the time obtained from the record at the beginning of the interval to the record at the end of the interval. I did with this code and got good result up to a point. Could you give me tips on how to get an assertive result in this case?

$totalhour = ($th.".".$tm) - ($totalbreak);

I tried to get the total time by subtracting the break time, but without success.



via Chebli Mohamed

mercredi 30 novembre 2022

getting error on server(aws) SyntaxError: Unexpected token '<', "

I have deployed my laravel application on AWS server(ubuntu). Application works fine. But when I upload images using custom modal popup, then i got the syntax error from vendors.js.

Here is the error getting from modal popup while uploading images: Here is the error getting from modal popup while uploading images

Can anyone tell about that, how i can resolve that? I am just stuck from last two days.

I have tried run on server npm i body-parser And also re-add the file of vendors.js But same result.



via Chebli Mohamed

mardi 29 novembre 2022

Fatal error: Uncaught ReflectionException: Class IlluminateContractsHttpKernel does not exist

Fatal error: Uncaught ReflectionException: Class IlluminateContractsHttpKernel does not exist in C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php:788 Stack trace: #0 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php(788): ReflectionClass->__construct('IlluminateContr...') #1 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php(667): Illuminate\Container\Container->build('IlluminateContr...') #2 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php(615): Illuminate\Container\Container->resolve('IlluminateContr...', Array) #3 C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Foundation\Application.php(767): Illuminate\Container\Container->make('IlluminateContr...', Array) #4 C:\xampp\htdocs\erc_new\public\index.php(52): Illuminate\Foundation\Application->make('IlluminateContr...') #5 C:\xampp\htdocs\erc_new\server.php(21): require_once('C:\xampp\htdocs...') #6 {mai in C:\xampp\htdocs\erc_new\vendor\laravel\framework\src\Illuminate\Container\Container.php on line 788

auto it is showin the Kernel error. thought i have not made any changes. i have already tried checking the Kernel.php files. more over i have already deleated the vendor and composer.lock file and install the composer . But also getting the the above error.

Moreover I also have deleted the every things that recedes on bootstrap/cache/



via Chebli Mohamed

Laravel 8 - search paginate ( withQueryString ) not working on table when searching NUMBERS on row integer

i can't search when it comes to searching NUMBERS on row int (price), but when searching like String number on row string (name) it's working fine

like this in my table row here is my Product table

category_id
"56"
user_id
"1"
name
"555"
description
"fruit"
price
555

when i am searching the name row "555" it's working fine beacuse its a string. but when it comes to price i can't search it because it's int

here is my code for controller searching

public function index(Request $request){
    $user = Auth::user()->id;
    if($request->search){
        $search = $request->search;
        $products = Products::with('category')
        ->where('name','like',"%$search%")
        ->orWhere('price','like',"%$search%")
        ->where('user_id',$user)->paginate(10);
    }else{
        $products = Products::with('category')->where('user_id',$user)->paginate(10);
    }
      return view('client.product.index',['products'=>$products]);
}

here is my blade

    <form class="w-full" action="">
        <i class="fa fa-search"></i>
        <input placeholder="Search"  type="search" name="search">     
        <button type="submit">Search</button>
    </form>

@foreach ($products as $product)
    <p></p>
    <p></p>
@endforeach



via Chebli Mohamed

lundi 28 novembre 2022

How to sort parent data based on child column detial in laravel 5.4?

I have 3 way relationship firstl i have get code like this in a controller

Trial::with('subjects')->where('source_id', $sourceId)->get()->toArray()

Now I want to sort subject.reactions on desc order of subject.reactions.accounts.nb_followers column. I tried to use orderby on relationship but it does not work because it sorting account indsted on reactions. I want to sort reaction based on value of "nb_followes" column present inside account table.

Trail Model

class Trial extends Model
{
    use HasFactory;
    public $table = 'trials';

    public function subjects()
    {
        return $this->hasMany(Subject::class, 'trial_id')->with(['reactions', 'news'])->withCount('reactions');
    }
  } 

Subject Model

class Subject extends Model
{
    use HasFactory;
    public $table = 'subjects';

    public function reactions()
    {
        return $this->hasMany(Reaction::class, 'subject_id', 'id')->with(['accounts' => function ($q) {$q->orderBy('nb_followers', 'DESC');}])->where('twitter_error', 0)->where('active', 1)->orderby('key_reaction', 'DESC');
    }

    public function news()
    {
        return $this->hasone(News::class, 'id', 'news_item_id');
    }

Reaction Model

class Reaction extends Model
{
    use HasFactory;

    public $table = 'reactions';

    public function accounts()
    {
        return $this->belongsTo(Account::class, 'account_id', 'id')->where('name', '!=', '');
    }

Thank you in Advance.



I want to sort reactions based on account table's column yes i cant use simple eloquent query because it will not create a structure that i want so that's why i created these relationships.


via Chebli Mohamed

vendredi 25 novembre 2022

500 error when image upload with Laravel 5.8 on nginx server

I'm getting 500 internal error when i try to upload 20kb image file.

I was checked following steps for finding to solution but it doesn't work :

  • I have hidden input for csrf token
  • I checked my storage and bootstrap folder for chmod 755 but they have permission.
  • My public folder has 777 permission
  • When i change app_env=local and app_debug=true there is no diffrent error.
  • There is no error log in storage/logs
  • When i try to submit form without image it worked.
  • there is no specific error in nginx logs (var/log/nginx/error.log)

I'm trying to upload image with laravel form in nginx server but i get 500 internal server error.



via Chebli Mohamed

How can I pass params at access point of GraphQL such as {url}/graphql?development=true by using lighthouse in laravel

How can I pass params at access point of GraphQL such as {url}/graphql?development=true by using lighthouse in laravel. if development is true i want to use different database in laravel.

http://127.0.0.1:8000/graphql?development=true

its working but graphql does not getting development params



via Chebli Mohamed

jeudi 24 novembre 2022

Error Laravel\Socialite\Two\InvalidStateException In the return method from the Google side

I want use Socialite package but receive in Error !

controller codes :

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\User;
use Laravel\Socialite\Facades\Socialite;

class GoogleAuthController extends Controller
{
    public function redirect()
    {
        return Socialite::driver('google')->redirect();
    }

    public function callback()
    {
        // when i dd() here i see in the answer in the browser.
        $googleUser = Socialite::with('google')->user();
        // but dd in here isn't working!
       
        $user = User::where('email', $googleUser->email)->first;

        if ($user) {
            auth()->loginUsingId($user->id);
        } else {
            $newUser = User::create([
                'name' => $googleUser->name,
                'email' => $googleUser->email,
                'password' => bcrypt(\Str::random(16)),
            ]);
            auth()->loginUsingId($newUser->id);
        }
        return $this->redirect('/');
    }
}

in web.php :

Route::get('auth/google', 'Auth\GoogleAuthController@redirect')->name('auth.google');
Route::get('auth/google/callback', 'Auth\GoogleAuthController@callback');

laravel version : 6.20.26

php version : 7.2.5

please help me. tnks

===============================================================

I try this (https://stackoverflow.com/a/37849202/20355717) :

Socialite::driver('google')->stateless()->user()

but in did't work for me and given an anothe error ! :

GuzzleHttp\Exception\RequestException

cURL error 77: error setting certificate verify locations: CAfile: /path/to
/downloaded/cacert.pem CApath: none (see https://curl.haxx.se/libcurl
/c/libcurl-errors.html) for https://www.googleapis.com/oauth2/v4/token


http://localhost:8000/auth/google/callback?authuser=0&code=4%2F0AfgeXvucuWTlboWqaMwf2bkBe0AHjbPEJd-
2e7cQdlSN345_3imguhVT_1PQ8fa3ISoHSA&prompt=consent&
scope=email%20profile%20openid%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile%20https%3A%2F
%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&
state=axIlfjFkns6vWNJIX2uJMuMKNiYFfy7cKiE8Xr8W 



via Chebli Mohamed

lundi 21 novembre 2022

Laravel 9 Validation: array is optional but its keys are required: required_array_keys and nullable don't work together

Summary

  1. Context

  2. Sources

    2.1. Unit test

    2.2. FormRequest's rules method

  3. Behaviors

    3.1. Actual behavior

    3.2. Expected behavior

  4. Question


Context

In a Unit test, I want to send data to a FormRequest in a REST call. I am testing the behavior of the validation rules I've written in the rules method of the FormRequest.

Sources

Unit test

    public function test_detach_user_job_status()
    {
        $response = $this->put(route('users.update', ['user' => $this->applier['id']], [
            'job' => [
            ]
        ]));
        $response->assertStatus(200);
    }

FormRequest's rules method

    public function rules()
    {
        return [
            'name' => 'nullable|string',

            'job' => 'nullable|array:id,attach_or_detach,message|required_array_keys:id,attach_or_detach',
            'job.id' => 'integer|gt:0',
            'job.attach_or_detach' => 'boolean',
            'job.message' => 'required_if:job.attach_or_detach,true|string',
        ];
    }

Behaviors

Actual behavior

The test succeeds.

Expected behavior

The test fails. Indeed, the array job is provided but no keys id or attach_or_detach or (eventually) message are provided, whereas the validation rules do specify: required_array_keys:id,attach_or_detach.

Also, if no job array is specified at all, then the validator must not reject the request because this array is not provided, nor its keys: it's perfectly normal since the array must be optional (it is nullable to provide this feature).

Question

Why doesn't Laravel make my test fail since my nullable (= optional) array is provided, and that its keys are required?



via Chebli Mohamed

dimanche 20 novembre 2022

Fetch product first based on values in column laravel

I have this query that fetches properties from table

$properties = Property::with('Category')
            ->orderBy('name','asc')
            ->where('status','Active')
            ->get();

In my table i have added new column featured it's value is either 0 or 1. I want to show property with 1 value in featured column first

Please suggest solution Thanks.



via Chebli Mohamed

samedi 19 novembre 2022

How can I ad more fields for the enrollment and make it appear on the dashboard

So I downloaded this project of laravel from github a laravel course enrollment project and I want to add more fields to the register form and make it appear on the admin panel as well but in with the code, they used the quickadminpanel.com and also repeating this cruds.enrollment.fields.user which is literally not defined any where in the code that I can see. Since I am a beginner with this laravel thing, I could really use some help in building a project using that repository. Thank You

I have tried almost every thing I know and so far...nothing is happening



via Chebli Mohamed

how to pass register data api to another out api

I am have register api for register user data in my users table I want also in the same register api set link for out api to register the same date also in another application how can i do this



via Chebli Mohamed

vendredi 18 novembre 2022

419 page expired error in laravel form submission even after adding csrf

 <form action="/checklogin" method="post" enctype="multipart/form-data" class="account-form" id="login_form_order_page">
                                     
              <div class="error-wrap"></div>
              <div class="form-group">
                 <input type="text" name="email" class="form-control" placeholder="Email*" required>
              </div>
              <div class="form-group">
                 <input type="password" name="password" class="form-control" placeholder="Password*" required>
              </div>
              <div class="form-group btn-wrapper">
                 <button type="submit" id="login_btn" class="submit-btn">Login</button>
              </div>
              <div class="row mb-4 rmber-area">
                 <div class="col-6">
                    <div class="custom-control custom-checkbox mr-sm-2">
                       <input type="checkbox" name="remember" class="custom-control-input" id="remember">
                       <label class="custom-control-label" for="remember">Remember Me</label>
                    </div>
                 </div>
                 <div class="col-6 text-right">
                    <a class="d-block" href="/register">Create New account?</a>
                    <a href="login/forget-password">Forgot Password?</a>
                 </div>
              </div>
              <div class="col-lg-12">
                 <div class="social-login-wrap">
                 </div>
              </div>
           </form>


Route::POST('/checklogin', 'HomeController@checklogin');

I am submitting the form with csrf still after submitting form 419|Page Expired Error. After adding session_start() method on page it shows headers already sent.



via Chebli Mohamed

mercredi 16 novembre 2022

lluminate\Database\Grammar::parameterize(): Argument #1 ($values) must be of type array, string

I have a problem trying to send values in the form of an array from the input, what is the solution? I searched a lot, but I did not find a solution to this problem. Can someone help me? Thank you

//blade

<td>
    <input type="text" class="qty form-control" name="p_unit[]">
    @error('p_unit.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td>
    <input type="text" class="qty form-control" name="p_lastPrice[]">
    @error('p_lastPrice.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td>
    <input type="text" class="qty form-control" name="p_averagecost[]">
    @error('p_averagecost.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td><input type="text" class="form-control" name="p_priceA[]"></td>
<td>
    <input type="text" class="form-control weight" name="p_priceB[]">
    @error('p_priceB.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>
<td>
    <input type="text" class="form-control unit_cost" name="p_priceC[]">
    @error('p_priceC.*')
    <div class="alert alert-danger" role="alert">
        
    </div>
    @enderror
</td>


I have an activated button that repeats the same fields to fill them in again, and after that I want to send the data in an array to the database

// controller

$products = $request->p_code;


for ($i=0; $i<count($products); $i++)
{
    $items = productUnitPrice::create([
        'p_code'               => $request->p_code,
        'p_packing'            => $request->p_packing[$i],
        'p_conversionfactor'   => $request->p_conversionfactor[$i],
        'p_unit'               => $request->p_unit[$i],
        'p_lastPrice'          => $request->p_lastPrice[$i],
        'p_averagecost'        => $request->p_averagecost[$i],
        'p_priceA'             => $request->p_priceA[$i],
        'p_priceB'             => $request->p_priceB[$i],
        'p_priceC'             => $request->p_priceC[$i],

    ]);


via Chebli Mohamed

My Laravel Links keep breaking Each time I restart my server

My Laravel links keep breaking each time I restart my local server

So, I am using Laravel 9 and my links keep breaking each time I reload the page or when I restart the server For example

127.0.0.1:8000/cars/1/edit

will become 127.0.0.1:8000/cars/cars/1/edit next time I click it.

I have searched for a solution and stumbled upon this On every click link changes in blade view

But the problem is that the guy that asked the question is using named routes from web.php route

I, on the other hand, am using resource routes ( I do not know what to call them = Route::resource('/cars', CarsController::class);)Resouce route

For that reason, I'm finding it difficult to implement the route() solution proposed as his had a named route name

The href I want to make changes to looks like this. I am using resources routes in web.php

<a href="cars//edit">Edit &rarr;</a>

Href I want to edit



via Chebli Mohamed

Tom-Select options not loading while using JavaScript's native Fetch API in this example to retrieve remote data from a route

I am attempting to load tom-select options not loading while using JavaScript's native Fetch API in this example to retrieve remote data from a route. However, JS below fetches a json array of 15527 items but won't show on the options

The Select element...

The JS...

var new_opd1 = "";

 new TomSelect('#select-repo',{
    valueField: 'url',
    labelField: 'icd_name',
    searchField: 'icd_name',
    // fetch remote data
    load: function(query, callback) {
        var url =new_opd1+'?q='+query ;
       // console.log(url)
        fetch(url)
            .then(response => response.json())
            .then(json => {
                //console.log(json.name); ~undefined
                callback(json);
               // console.log(json);
            }).catch(()=>{
            callback();
        });

        
    },
   // custom rendering functions for options and items
     render: {
        option: function() {
            return `<div class="py-2 d-flex">
                        <div>
                            <div class="mb-1">
                                <span class="h4">
                                    ${(icd_name) } 
                                </span>
                            </div>
                            <span class="h4">
                                    ${(icd_code) }
                                </span>
                        </div>
                    </div>`;
        },
        item: function() {
            return `div class="py-2 d-flex">
                        <div>
                            <div class="mb-1">
                                <span class="h4">
                                    ${(icd_name) }
                                </span>
                            </div>
                            <div class="description">${(icd_code) }</div>
                        </div>
                    </div>`;
        }
    },


 });
The route...

public function getData(Request $request){

$users = ICD10Code::project(["_id" => 0])->get(['icd_code','icd_name']);

return json_encode($users->toArray());

}



I am attempting to recreate this https://tom-select.js.org/examples/remote/. However since my dataset is huge I was wondering if really this would work



via Chebli Mohamed

mardi 15 novembre 2022

Exclude from a select more than 2101 records with laravel sql query builder

I am using something like this:

$scanned = DB::table("Persons")
        ->whereNotIn("Person_Id", $exclude)
        ->get();

The problem is $exclude has more than 2101 records, and I get the following error:

SQLSTATE[IMSSP]: Tried to bind parameter number 2101.  SQL Server supports a maximum of 2100 parameters.

Is there a way around? how can I solve this?



via Chebli Mohamed

lundi 14 novembre 2022

Is there any way to use eloquent addSelect with different database on a different server in Laravel?

A table called api_call_data is being used in a seperate database (done by the original code author, not me) which is located in another server in our Laravel project (I can't move the table).

Due to that, the original query doesn't work anymore. The original query was like below:

$apicallData->addSelect(DB::raw("
    (SELECT MAX(`reg_time`) FROM `api_call_data` as A WHERE `A`.`app_id` = `apps_data`.`app_id` and reg_time between $request->from_date and $request->to_date) as api_reg_time
"))

(I have omitted the rest of the queries after this here)

Is there any way to make this original query work? I really wanted to make this work but I am totally lost here.



via Chebli Mohamed

dimanche 13 novembre 2022

Wildcard routing with laravel not following recognizing prefix

In my application i have a laravel backend with two spas consuming api from it. Now i want to manage my routes by using wildcard routes where i give both routes prefixes before the wildcard route takes effect. Here is an example

Route::prefix('creditors')->group(function () {
    Route::any('/{all}', function () {
        return view('creditor');
    })->where(['all' => '.*']);
});

Now the issue us if i visit something like /creditors/login the spa returns a 404 not found. I want my spa to start handling routing after "creditors/". How do i go about this?



via Chebli Mohamed

samedi 12 novembre 2022

vendredi 11 novembre 2022

Can config/auth.php be made dynamic?

Can helper functions or through any other medium be used to make changes in config/auth.php? I mean can we get some data from the database through helper function or some other way and just append the data to config/auth.php.

I was trying to append the data to guards key. I made a guards table and formatted the data to the exact format of guards key of config/auth.php.

I called a helper function in config/auth.php and tried to get the data of guards but it showed a bunch of errors.



via Chebli Mohamed

jeudi 10 novembre 2022

CSRF token mismatched in laravel when i moved project to another server

enter image description here

Hii My website is not working on other server code is same into both server

1, Working server

http://programmingly.com/articles/

  • testuser@gmail.com
  • 12345678 (Working perfect)

https://www.vennocracy.com/

  • testuser@gmail.com
  • 12345678 (Not Working)

I tried ajax for that

$('#login-form').validate({
        rules: {
            email: {
                required: true,
            },
            password: {
                required: true,
            },
        },
        messages: {
            email: {
                required: 'Please enter email',
            },
            password: {
                required: 'Please enter password',
            },
        },
        submitHandler: function(form) {
            $.ajax({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                url: "",
                type: "POST",
                data: new FormData(form),
                dataType: 'json',
                contentType: false,
                cache: false,
                processData: false,
                beforeSend: function() {
                    $("body").append(
                        "<div class='ajax-overlay'><i class='porto-loading-icon'></i></div>"
                        );
                },
                success: function(res) {
                    $(".ajax-overlay").remove();
                    if (res.status) {
                        $('.all-error').html('');
                        $('.all-success').html('');
                        $('.all-success').html(res.message);
                        setTimeout(function() {
                            $("#loginModal").modal('hide');
                            location.reload();
                        }, 4000);
                    } else {
                        $('.all-error').html('');
                        $('.all-error').html(res.message);
                    }
                },
                error: function(data) {
                    $(".ajax-overlay").remove();
                    var errorString = '';
                    $.each(data.responseJSON.errors, function(key, value) {
                        errorString += value + '<br>';
                    });
                    $('.all-error').html('');
                    $('.all-success').html('');
                    $('.all-error').html(errorString);
                },
            });
            return false;
        }
    });


via Chebli Mohamed

mercredi 9 novembre 2022

What benefit is there in using artisan auth:clear-resets? Does it prevent certain issues or only maintains table size?

Does artisan auth:clear-resets do anything besides clearing the password_resets table? Does this affect the functionality of the password reset system?

I've been having some problems where our users trigger a password reset but as soon as they click through in the provided email they get an "invalid token" notice. I use artisan auth:clear-resets and it seems that the complaints go away...

It could be a coincidence but I was wondering if there was an underlying benefit to clearing the password_resets table that I'm unfamiliar with



via Chebli Mohamed

Laravel, download 2 files on one button click

I'm trying to make a feature where one button being clicked will access a single route and controller but the controller will sequentially download 2 files. The catch is they can't be zipped, they need to be downloaded sequentially as single files.

I've tried with this but I get an array to string conversion error.

public function fileDownload(){

    $first_file_name = 'test.xlsx';
    $first_file_path = storage_path("files/{$first_file_name}");

    $second_file_name = 'test2.xlsx';
    $second_file_path = storage_path("files/{$second_file_name}");  

    return \Response::download([$first_file_path, $second_file_path]);
}

Is there a way to do this in Laravel 5.3?



via Chebli Mohamed

how to show multiple filenames in one json format?

I'm not sure where and how I should use the for loop.

I am using Laravel v5.5. I am trying to upload multiple files on my project. I think if I can add all filenames in one json array I can show them in blade page. How can i do that?


        if(request()->hasFile('urun_resmi')) {
            $files = request()->file('urun_resmi');
            $filename = [];
            foreach ($files as $file) {
                if($file->extension() == 'pdf')
                {
                    $filename = $file->extension() . "-" . $entry->id . "-" . time() . "." . $file->extension();
                }else
                {
                    $filename = $entry->id . "-" . time() . "." . $file->extension();
                }
                $file->storeAs('urunler', $filename, 'public');
                $entry->detay()->update(['urun_resmi' => $filename]);
                
          
                if ($file->isValid()) {
                    $file->move('uploads/urunler', $filename);
                    UrunDetay::updateOrCreate(
                        ['urun_id' => $entry->id],
                        ['urun_resmi' => $filename]
                    );
                }
            }

        }


via Chebli Mohamed

mardi 8 novembre 2022

laravel log debug is not working.I checked A response is returned from the server side

laravel log debug is not working.

I create app with laravel5 and vue.js.

I send a request to the server side with vue and catch this with laravel Controller.php.

I code Log::debug to PostsController.php, but the log is not written in laravel.log.

I try use Illuminate\Support\Facades\Log; and use Log; , but both are not working.

Do you find anything wrong with my code?

Thank you for your help.

// web.php

Route::get('/posts/items', 'PostsController@items');
PostsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use App\Model\Post;
use App\Model\Item;
// use Log;
use Illuminate\Support\Facades\Log;

use App\Http\Resources\Post as PostResource;
use App\Http\Resources\Item as ItemResource;

class PostsController extends Controller
{

    public function items(Request $request)
    {
        Log::info('kita');
        Log::debug('kurukao');
        logger()->debug('debug');

        $post_id = $request->input('post_id');
        return $post_id;
    }

//vue


    methods: {
      mouseenter(id) {
        this.itemId = id;
      },
      mouseleave(id) {
        this.itemId = null;
      },
      getItems() {
        axios.get("/posts/items", {
            post_id: this.$route.params.id
        })
        .then((res) => {
        //   console.log(res.data)
          console.log('ok')
          this.postDataList = res.data.data;
        //   console.log(this.postDataList)
          if(this.postDataList != null){
            this.itemDataList = this.postDataList[0]['items'];
          }
        });
      },


via Chebli Mohamed

I type php artisan make:migartion ... and php artisan migrate, but table was not created

I create laravel5,mysql8 environment with docker-compose. I create post table with laravel migration. but I entered mysql container and checked if the table was created, but the table was not created.

I type php artisan make:migration create_posts_table and It works. Then, I did the following. enter image description here

as pictured, table is not exist. why is this? Thank you for your help.

enter image description here

enter image description here



via Chebli Mohamed

lundi 7 novembre 2022

Laravel 5.6: sending email to BCC without adding email in TO()

How to send email to only bcc() without to(). When I tried, I got error

Error Information.

URL: http://example.com Parameters: [] Request Name: Request Method: GET Line Number: 309 File: /var/www/html/project_name/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php Client IP: 127.0.0.1 HTTP Referer: Is Secure: Is Ajax: userAgent: Symfony content: Error Message: Whoops! There was an error. ErrorException (E_WARNING) Illegal string offset 'address' ErrorException thrown with message "Illegal string offset 'address'" Stacktrace: #38 ErrorException in /var/www/html/project_name/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php:309 #37 Illuminate\Foundation\Bootstrap\HandleExceptions:handleError in /var/www/html/project_name/vendor/laravel/framework/src/Illuminate/Mail/Mailable.php:309

Sending email to all bcc without using to



via Chebli Mohamed

I want to get the list of users who were present in the club from 10 AM to 12 PM using an SQL query in Laravel eloquent

thank you for reading this issue. please help me with the below issue

I want to user list which users in the club at the time between

  • 022-11-07 11:32:48 - 2022-11-07 12:32:48

below is data store in DB

  • In Time--------------------Out Time----------------- be show in result

  • 2022-11-07 11:32:48 - 2022-11-07 12:32:48 => 1

  • 2022-11-07 10:32:48 - 2022-11-07 11:33:00 => 1

  • 2022-11-07 12:32:00 - 2022-11-07 13:32:00 => 1

  • 2022-11-07 11:45:00 - 2022-11-07 12:15:00 => 1

  • 2022-11-07 10:00:00 - 2022-11-07 13:00:00 => 1

  • 2022-11-07 09:30:00 - 2022-11-07 11:30:00 => 0

  • 2022-11-07 12:35:00 - 2022-11-07 13:32:48 => 0

$activity = Activity::findOrFail($activity_id);

$users = User::whereHas('activities', function ($q) use ($activity) {
   $q->where('activities.activity_id', $activity->activity_id);
})->whereHas('bookingActivities', function ($query) use ($booking) {
   $query->whereNull('cancelled_by')
   ->whereBetween('bookingActivities.entry_time', [$booking->entry_time, $booking->exit_time])
   ->orWhereBetween('bookingActivities.exit_time', [$booking->_entry_time, $booking->exit_time]);
})->paginate();

I have add the query and it will give me 4 result it Should be 5

please help me to how can i add the query so i can get expect result.

thanks in advance



via Chebli Mohamed

samedi 5 novembre 2022

Laravel Fatal error: Uncaught ReflectionException: Class App\Http\Kernel does not exist

Tried to install ** maatwebsite/excel** using composer as,

composer require maatwebsite/excel

but it throws Kernel does not exist error.

There are kernel files in the following locations

app\Console\Kernel.php app\Http\Kernel.php

Also tried composer update, composer dump-autoload. Tried deleting vendor folder and then composer install

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.3|^8.0",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^7.0.1",
        "laravel/framework": "^8.12",
        "laravel/tinker": "^2.5",
        "laravel/ui": "^3.2",
        "maatwebsite/excel": "^3.1"
    },
    "require-dev": {
        "facade/ignition": "^2.5",
        "fakerphp/faker": "^1.9.1",
        "laravel/sail": "^1.0.1",
        "mockery/mockery": "^1.4.2",
        "nunomaduro/collision": "^5.0",
        "phpunit/phpunit": "^9.3.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true,
        "platform-check": false
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

```
`

How do i resolve this issue.


via Chebli Mohamed

vendredi 4 novembre 2022

WhatsApp API integration in Laravel not working

I have issue in my laravel project, the code below is working fine in core php, but it's not workng in laravel

i'm using old laravel version 5.5

even not showing any error

please help me ASAP, i hava a deadline

please help me ASAP, i hava a deadline please help me ASAP, i hava a deadline

`if($request->has('whatsapp') && $request->whatsapp!=0){
                $url = "https://graph.facebook.com/v15.0/{key}/messages";

$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('{auth key}', 'Content-Type: application/json'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$data3 = [
  
    "type"=>"body",
    "parameters" => [
      "type"=>"text",
      "text" => "Mr Jibran"
    ]
];

$data2 = [
  "name"=>"sample_issue_resolution",
"language"=> ["code"=> "en_US" ],
"components" => $data3
];

/*
components:{
  type:body,
  parameters {
    type:text,
    text:Mr Jibran
  }}"

*/

$data = array(
  "messaging_product"=>"whatsapp",
  "to"=>"my number",
  "type"=>"template",
  "template"=> array(
    "name"=>"sample_issue_resolution",
    "language"=> array ("code"=> "en_US" ),
    "components" => array(
      ["type"=>"body",
    "parameters" => array(
      ["type"=>"text",
      "text" => "Mr Jibran"]
    )]
    )
  )
)
;



$fields_string = json_encode($data);

curl_setopt($curl, CURLOPT_POSTFIELDS, $fields_string);

$resp = curl_exec($curl);
curl_close($curl);

echo $resp;
                
            }

        }

    }`


via Chebli Mohamed

jeudi 3 novembre 2022

Instance class by some rule

I have some function converting some tag to class name.

function($tag): string {
    return '\App\Services\MyUglyServices\' . ucfirst(Str::camel($tag));
}

I want to instance some class by corresponding tag name. For example:

$obj = app('tag:my_ugly_service');
echo get_class($obj); // I want it to be \App\Services\MyUglyServices\MyUglyService

Is there any way to do it using service providers?



via Chebli Mohamed

mardi 1 novembre 2022

Laravel 5 User::where() My where call isn't working with laravel 5

I have narrowed my error down to this line of code

$user= User::where(['email'=>$req->email])->first();

it it not working with Laravel 5 I think this is from a Laravel 4 project. How do I update it to 5?



via Chebli Mohamed

Why my excel import date format is not working in laravel

I try to import the excel data file but my date format is not working. other than that data import is working file only issue is in the date format Please help to solve this issue.

enter image description here

this is my import code.

<?php

namespace App\Imports;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Carbon;

use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;

use App\student_import;

use App\centres;
use App\Course;

class ImportStudent implements ToModel,WithHeadingRow
{
    /**
    * @param Collection $collection
    */

    public function model(array $row)
    {
        $rowNumber = array_values($row);

        $insert_data[] = array(
            'stud_dob' => Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($rowNumber[8])),
            'stud_gender' => $rowNumber[9],
            'stud_add1' => $rowNumber[10],
            'stud_nationality' => $rowNumber[13],
            'stud_registration_date' => Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($rowNumber[14])),
            'stud_completion_date' => Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($rowNumber[15])),
            'stud_course_status' => $rowNumber[16]
        );

    }
}

This is the error I'm getting when import the data file

enter image description here

enter image description here



via Chebli Mohamed

lundi 31 octobre 2022

Laravel taking 100% MySQL DB CPU and no jobs visible in php artisan queue:listen, Laravel 5.7

The MySQL DB CPU is running at 95%+ basically at all times, even when there's seemingly no activity in the app. It doesn't happen right away. Only once the app has been running for a while, but then it keeps at 95% CPU even once there's seemingly no activity.

The number of active sessions / connections gradually climbs from dozens to even hundreds. Looking at the MySQL processes on RDS reveals a dozen processes trying to use 8% of the DB CPU each for some reason.

I've checked for Laravel jobs via php artisan queue:listen but nothing appears.

Checked the database and query logs, and there are many DB logs which suggest a job or something occurring in a loop, but no indication as to what the source of those jobs are as the queries being ran are generic queries and could be called from many different places in the application.

We do not believe this is due to user activity, but if it is, it's some kind of user action whicih results in some kind of a server loop.

Checked application and error logs and nothing in particular stands out.



via Chebli Mohamed

when i upload laravel website form local to live sever this error that i face can any one help me

SQLSTATE[HY000] [2002] Connection refused (SQL: select * from sessions where id = E70KsnO9rKtK9ATW71zmd9AfGW1ek7nAhnD2wQjS limit 1) error that i face

any one help me to solve this



via Chebli Mohamed

samedi 29 octobre 2022

Laravel clearing config causing wierd X to show up

I'm currently using laravel 5.8 in a project and stumbled on a weird problem, after lanching the commande optimize:clear a Wierd Caracheter will show up when executing any other commande and also causing ajax requests to fail here is an example of the problem enter image description here

this happening in all the team machines, not just mine. the second problem reloading a page, every time We load a page we see this screen before it redirected to the actual view
enter image description here

the only found solution is to run the commande Artisan config:cache



via Chebli Mohamed

vendredi 28 octobre 2022

how to improve my performance for this complex query | Laravel , Datatabels

Hi everyone i have a very complex query to get Finance data, its like 4 Join and when the data is more than 1000 it getting slow when it loads in datatables how i can make it faster

this is the controller code for ajax :

  $financial_entries = FinanceEntryMod::select([
        DB::raw("ROUND(( 
            select SUM(finance_transaction.equivalent) from finance_transaction  where 
            finance_transaction.entry_id = financial_entries.id and
            finance_transaction.type = 'credit' 
        ), 2) as eqivalent_sum"),
        'financial_entries.id',
        'financial_entries.created_by',
        'financial_entries.branch_id',
        'financial_entries.order_id',
        'financial_entries.number',
        DB::raw('IFNULL(branches.name, IFNULL(v2_branches.name, "main_branch")) AS branch_name'),
        'financial_entries.v2_order_id as v2_order_id',
        'financial_entries.v2_document_id as v2_document_id',
        'financial_entries.date',
        'financial_entries.is_generated',
        'financial_entries.note',
        'financial_entries.created_at',
        'financial_entries.updated_at',
        DB::raw('
            DATE_FORMAT(financial_entries.date, "%Y-%m-%d") AS new_date,
            DATE_FORMAT(financial_entries.created_at, "%Y-%m-%d") AS new_created_at
        ')
    ])
    ->leftJoin('branches', function ($join) {
        $join->on("branches.id", "=", "financial_entries.branch_id");
    })
    ->leftJoin('finance_transaction', function ($join) {
        $join->on("financial_entries.id", "=", "finance_transaction.entry_id");
    })
    ->leftJoin('finance_accounts', function ($join) {
        $join->on("finance_accounts.id", "=", "finance_transaction.account_id");
    })
    ->leftJoin('v2_branches', function ($join) { 
        $join->on("v2_branches.id", "=", "finance_accounts.v2_branch_id"); 
    })
    ->where('financial_entries.is_deleted', '=', '0')
    ->groupBy('financial_entries.id');

and in the script : im using this

   "pageLength": 30,
        "serverSide"   : true,
        "processing"   : true,
        "columns": 

please help me to improve it thanks all



via Chebli Mohamed

jeudi 27 octobre 2022

MethodNotAllowedHttpException at RouteCollection->methodNotAllowed(array('POST'))

I'm trying to use POST to let user log in with correct email/password. I keep getting this error

MethodNotAllowedHttpException at RouteCollection->methodNotAllowed(array('POST'))

web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;

Route::get('/', function () {
    return view('login');
});

Route::post("/login",[UserController::class,'login']);

UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    //
    function login(request $req)
    {
        return $req->input();
    }
}

login.blade.php

@extends('master')
@section('content')
<div class="container custom-login">
    <div class="row">
        <div class="col-sm-4 col-sm-offset-4">
            <form action="/login" method="POST">
            <div class="form-group">
                @csrf
                <labe for="exampleInputEmail">Email address</label>
                <input type="email" name="email" class="form-control" id="exampleInputEmail" placeholder="Email">
            </div>
            <div class="form-group">
                <labe for="exampleInputPassword">Password</label>
                <input type="password" name="password" class="form-control" id="exampleInputPassword" placeholder="Password">
            </div>
            <button type="submit" class="btn btn-default">Login</button>
            </form>
        </div>
    </div>
</div>

@endsection

I tried opening the login page but POST is having issues. I expected the login page to use POST to check credentials in my database.



via Chebli Mohamed

mercredi 26 octobre 2022

How to make clean code laravel in my case

Hi i need to make this code clean to reduce performance from serve how can do that ? the code have request search, filter and export must change all code to have small code

Hi i need to make this code clean to reduce performance from serve how can do that ? the code have request search, filter and export must change all code to have small code

need to change this code to clean code with best performance in server

//request search
if ($request->filled('search')) {

            // $users = User::search($request->search)->paginate(10);

            $users = User::query()
                ->withCount('orders')
                ->where('id', 'Like', '%' . request('search') . '%')
                ->orwhere('first_name', 'Like', '%' . request('search') . '%')
                ->orwhere('last_name', 'Like', '%' . request('search') . '%')
                ->orwhere('mobile', 'Like', '%' . request('search') . '%')
                ->orwhere('email', 'Like', '%' . request('search') . '%')
                ->paginate(10);
//if have request search and need to check for export files and sort
            if ($request->filled('filter') or $request->filled('export')) {

                if ($request->filter == 0 and $request->export == 1) {
                    $users;
                    $pdf = Pdf::loadView('myPDF', compact('users'));
                    return $pdf->download('itsolutionstuff.pdf');
                } elseif ($request->filter == 0 and $request->export == 2) {
                    $users;
                    return Excel::download(new UsersExport($users), 'users-collection.xlsx');
                } elseif ($request->filter == 0 and $request->export == 3) {
                    $users;
                    return (new UsersExport($users))->download('Alphabetical.csv', \Maatwebsite\Excel\Excel::CSV);
                } elseif ($request->filter == 0) {
                    $users;
                }

                if ($request->filter == 1 and $request->export == 1) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('first_name')->paginate(10);
                    $pdf = Pdf::loadView('myPDF', compact('users'));
                    return $pdf->download('itsolutionstuff.pdf');
                } elseif ($request->filter == 1 and $request->export == 2) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('first_name')->paginate(10);
                    return Excel::download(new UsersExport($users), 'users-collection.xlsx');
                } elseif ($request->filter == 1 and $request->export == 3) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('first_name')->paginate(10);
                    return (new UsersExport($users))->download('Alphabetical.csv', \Maatwebsite\Excel\Excel::CSV);
                } elseif ($request->filter == 1) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('first_name')->paginate(10);
                }

                if ($request->filter == 2 and $request->export == 1) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('orders_count', 'desc')->paginate(10);
                    $pdf = Pdf::loadView('myPDF', compact('users'));
                    return $pdf->download('itsolutionstuff.pdf');
                } elseif ($request->filter == 2 and $request->export == 2) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('orders_count', 'desc')->paginate(10);
                    return Excel::download(new UsersExport($users), 'users-collection.xlsx');
                } elseif ($request->filter == 2 and $request->export == 3) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('orders_count', 'desc')->paginate(10);
                    return (new UsersExport($users))->download('Alphabetical.csv', \Maatwebsite\Excel\Excel::CSV);
                } elseif ($request->filter == 2) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('orders_count', 'desc')->paginate(10);
                }

                if ($request->filter == 3 and $request->export == 1) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('orders_count', 'desc')->orderBy('first_name')->paginate(10);
                    $pdf = Pdf::loadView('myPDF', compact('users'));
                    return $pdf->download('itsolutionstuff.pdf');
                } elseif ($request->filter == 3 and $request->export == 2) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('orders_count', 'desc')->orderBy('first_name')->paginate(10);
                    return Excel::download(new UsersExport($users), 'users-collection.xlsx');
                } elseif ($request->filter == 3 and $request->export == 3) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('orders_count', 'desc')->orderBy('first_name')->paginate(10);
                    return (new UsersExport($users))->download('Alphabetical.csv', \Maatwebsite\Excel\Excel::CSV);
                } elseif ($request->filter == 3) {
                    $users = User::query()->withCount('orders')->where('id', 'Like', '%' . request('search') . '%')->orwhere('first_name', 'Like', '%' . request('search') . '%')->orwhere('last_name', 'Like', '%' . request('search') . '%')->orwhere('mobile', 'Like', '%' . request('search') . '%')->orwhere('email', 'Like', '%' . request('search') . '%')->orderBy('orders_count', 'desc')->orderBy('first_name')->paginate(10);
                }

            }
//if not have request search and need to make filter sort
        } elseif ($request->filled('filter')) {

            if ($request->filter == 1 and $request->export == 1) {
                $users = User::withCount('orders')->orderBy('first_name')->paginate(10);
                $pdf = Pdf::loadView('myPDF', compact('users'));
                return $pdf->download('itsolutionstuff.pdf');
            } elseif ($request->filter == 1 and $request->export == 2) {
                $users = User::withCount('orders')->orderBy('first_name')->paginate(10);
                return Excel::download(new UsersExport($users), 'users-collection.xlsx');
            } elseif ($request->filter == 1 and $request->export == 3) {
                $users = User::withCount('orders')->orderBy('first_name')->paginate(10);
                return (new UsersExport($users))->download('Alphabetical.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($request->filter == 1) {
                $users = User::withCount('orders')->orderBy('first_name')->paginate(10);


            } elseif ($request->filter == 2 and $request->export == 1) {
                $users = User::withCount('orders')->orderBy('orders_count', 'desc')->paginate(10);
                $pdf = Pdf::loadView('myPDF', compact('users'));
                return $pdf->download('Most_orders.pdf');
            } elseif ($request->filter == 2 and $request->export == 2) {
                $users = User::withCount('orders')->orderBy('orders_count', 'desc')->paginate(10);
                return Excel::download(new UsersExport($users), 'users-collection.xlsx');
            } elseif ($request->filter == 2 and $request->export == 3) {
                $users = User::withCount('orders')->orderBy('orders_count', 'desc')->paginate(10);
                return (new UsersExport($users))->download('invoices.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($request->filter == 2) {
                $users = User::withCount('orders')->orderBy('orders_count', 'desc')->paginate(10);


            } elseif ($request->filter == 3 and $request->export == 1) {
                $users = User::withCount('orders')->orderBy('id', 'DESC')->paginate(10);
                $pdf = Pdf::loadView('myPDF', compact('users'));
                return $pdf->download('Date_of_registration.pdf');
            } elseif ($request->filter == 3 and $request->export == 2) {
                $users = User::withCount('orders')->orderBy('id', 'DESC')->paginate(10);
                return Excel::download(new UsersExport($users), 'users-collection.xlsx');
            } elseif ($request->filter == 3 and $request->export == 3) {
                $users = User::withCount('orders')->orderBy('id', 'DESC')->paginate(10);
                return (new UsersExport($users))->download('invoices.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($request->filter == 3) {
                $users = User::withCount('orders')->orderBy('id', 'DESC')->paginate(10);


            } elseif ($request->filter == 0 and $request->export == 1) {
                $users = User::withCount('orders')->paginate(10);
                $pdf = Pdf::loadView('myPDF', compact('users'));
                return $pdf->download('Date_of_registration.pdf');
            } elseif ($request->filter == 0 and $request->export == 2) {
                $users = User::withCount('orders')->paginate(10);
                return Excel::download(new UsersExport($users), 'users-collection.xlsx');
            } elseif ($request->filter == 0 and $request->export == 3) {
                $users = User::withCount('orders')->paginate(10);
                return (new UsersExport($users))->download('invoices.csv', \Maatwebsite\Excel\Excel::CSV);
            } elseif ($request->filter == 0) {
                $users = User::withCount('orders')->orderBy('id', 'DESC')->paginate(10);
            }

        } else {
//if not have any request search
            $users = User::withCount('orders')->paginate(10);
        }
        return view('admin.users.index', compact('users'));


via Chebli Mohamed