jeudi 30 juin 2022

How to allow websockets through a Laravel 5.8 maintenance page?

I need to allow websockets wss:// through the maintenance mode with Laravel 5.8 as:

php artisan down --allow=xxx.xxx.xx.xx




php artisan down --allow=127.0.0.1

But no luck.

Any clever ideas please? Is there a way to allow on Laravel 5.8 a protocol like wss:// ? I cannot work out why the Laravel maintenance page blocks it. As soon as it is up, the websockets work again.

Thanks



via Chebli Mohamed

Laravel 5.4 - remember me and custom session values issue

I get project that has custom values in sessions. I use Remember me option, and every time when session is expired, new session is created (regenerated).

Now, I have problem because I need to keep all data from main session (first created) and keep values for all time that user is logged in .

Example:

if (Auth::attempt(['email' => $email, 'password' => $password], $rememberMe)) {
    $data = [
        'unread_messages'         => $message->unread_messages,
        'unread_worker_messages'  => $message->unread_worker_messages,
        'unread_poll'             => $message->unread_poll
        ];
        
        session(['num_unread_message' => $data]);
}

Now, when the session is expired after 2 hours, user will be logged, because Remember me is TRUE, but the values in Session get vanished.

I need to keep all of values in the new session that will be created after regeneration.



via Chebli Mohamed

mardi 28 juin 2022

Pusher In Laravel With Apiato

I Try manythinhg but still got error in pusher. This is very Common Error. Pusher/Pusher class not found. I try below i mention.

add class in config/app line 253) code : 'Pusher' => Pusher\Pusher::class

composer dump-autoload -> Output 0

Vendor directory delete -> composer install-> composer update

Accroding blog https://stackoverflow.com/questions/45052853/class-pusher-not-found-> PusherBroadCaster search and rename with Pusher-> output 0

Try to install pusher 7.0 output = error

Add Manually path->composer update-> output 0 and I Am use Laravel '5.5' with apiato core '2.2.6' and my pusher package version is '2.6'



via Chebli Mohamed

lundi 27 juin 2022

real time - browser

i have a problem, my search engine only searches with a particular Model

Model: 'Registro'

 public function search(Request $request){
        
        $results = Registro::where('cliente', 'LIKE', "%{$request->search}%")->get();
        
        return view('posts.results', compact('results'))->with(['search' => $request->search])->render();
        
    }

How can I make the search engine work with more Models?



via Chebli Mohamed

dimanche 26 juin 2022

Laravel RefreshDatabase doesn't work in testing

In order to move my current Laravel 5.5 project to the latest version, I was trying to setup some tests (I've never done that before).

To do so, I added <env name="DB_CONNECTION" value="mysql_testing" /> in the phpunit.xml, under the <php> section, and created a copy of the current mysql configuration under config/database.php naming it mysql_testing, which has 'database' => env('DB_NAME_TESTING', 'forge') .

In the .env file I put DB_NAME_TESTING=testDB. The database exists, is empty and the user has all permissions on it.

I haven't created any Test, yet, just tried the Examples provided by Laravel. If I run the tests as they are, they all pass. If I add the RefreshDatabase trait on them, instead, I get

ErrorException : Trying to access array offset on value of type int
C:\[path to project]\vendor\symfony\console\Input\ArrayInput.php:135

which corresponds to } elseif ('-' === $key[0]) {.

After a bit of tracing, I found out that the $key is 'migrate:fresh', which is the Artisan command that RefreshDatabase is trying to run. In later versions this segment has been replaced with } elseif (str_starts_with($key, '-')) {, but this is only available since PHP 8, and I'm currently stuck with PHP 7.4.

My question now is: what am I doing wrong in setting up my testing database?



via Chebli Mohamed

samedi 25 juin 2022

ErrorException Undefined variable: users (View: resources\views\admin\dashboard.blade.php)

hi I wants to show users list into my dashboard pannel but it shows me this problem :

ErrorException Undefined variable: users (View: resources\views\admin\dashboard.blade.php)

Controller File :

 public function index()
{
    $listuser = User::all();
    return view('admin.dashboard',['users' => $listuser]);
    //return view('admin.dashboard')->with('users', $listuser);
}

blade file :

 <div id="utilisateurs">
                            <table width="100%" cellspacing="0" border="1">
                                    <thead>
                                        <tr>
                                            <th>Id</th>
                                            <th>Nom et Prenom</th>
                                            <th>Email</th>
                                            <th>tele</th>
                                            <th>adresse</th>
                                            <th>date de creation</th>
                                            <th>Statut de compte</th>
                                        </tr>
                                    </thead><br>
                                    <tbody>
                                        
                                        @foreach($users as $user)
                                            @if($user->role_as=='0')
                                        <tr>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td></td>
                                            <td>Null</td>
                                        </tr>
                                            @endif
                                        @endforeach
                                    </tbody>
                            </table>
                        </div>

Routes :

  Route::middleware(['auth','isAdmin'])->group(function() {
Route::get('/dashboard','Admin\FrontendController@index');


/*users routes*/
Route::get('/dashboard', 'UserController@index');


via Chebli Mohamed

vendredi 24 juin 2022

I install the flutterwave package in laravel 8 and 9 but facing this issue

i run this command

composer install flutterwavedev/flutterwave-v3

give me this error.

Invalid argument flutterwavedev/flutterwave-v3. Use "composer require flutterwavedev/flutterwave-v3" instead to add packages to your composer.json.

when we run this command "composer require flutterwavedev/flutterwave-v3".

Your requirements could not be resolved to an installable set of packages.

Problem 1 - flutterwavedev/flutterwave-v3 1.0.0 requires monolog/monolog 1.* -> found monolog/monolog[1.0.0-RC1, ..., 1.x-dev] but the package is fixed to 2.6.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command. - flutterwavedev/flutterwave-v3 1.0.1 requires vlucas/phpdotenv ^2.5 -> found vlucas/phpdotenv[v2.5.0, ..., 2.6.x-dev] but the package is fixed to v5.4.1 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command. - Root composer.json requires flutterwavedev/flutterwave-v3 ^1.0 -> satisfiable by flutterwavedev/flutterwave-v3[1.0.0, 1.0.1].

Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.
You can also try re-running composer require with an explicit version constraint, e.g. "composer require flutterwavedev/flutterwave-v3:*" to figure out if any version is installable, or "composer require flutterwavedev/flutterwave-v3:^2.1" if you know which you need.

Installation failed, reverting ./composer.json and ./composer.lock to their original content.



via Chebli Mohamed

Call to a member function links() on array_push in laravel

I'm sending the two different queries resulting in one parameter using the array push method that time laravel pagination is not working. Without pagination queries working fine. I don't know what was the issue please help me how to fix this issue

My Query

public function searchProduct(Request $request)
{
$pro = array();
        foreach ($catePro as $cateProCode)
        {
            //dd($cateProCode);

            $max = DB::table('product')
                ->select(['product.prod_product_code', DB::raw('MAX(quab_quantity) AS qty')])
                ->LeftJoin('quantity_break', 'quab_product_code', '=', 'prod_product_code')
                ->where('prod_product_code', '=', $cateProCode->catpro_prod_code)
                ->paginate(12);


            foreach ($max as $wt)
            {
                $maCode = DB::table('product')
                    ->join('quantity_break', 'quab_product_code', '=', 'prod_product_code')
                    ->join('supplier','supp_code','=','prod_supplier_code')
                    ->select('prod_product_code','prod_supplier_code', 'product_name', 'prod_image1', 'prod_from_price', 'quab_quantity','supp_margin','prod_supp_margin','prod_seo_title')
                    ->where('prod_product_code', '=', $wt->prod_product_code)
                    ->where('quab_quantity', '=', $wt->qty)->where('supp_flag','=','1')
                    ->orderBy('supp_seq_no','ASC')
                    ->paginate(12);

                array_push($pro, $maCode);
                
                //$data = $this->paginate(array_push($pro, $maCode));

            }
        }

        $sysfromPrice = sysmaster::where('sysm_def_id','from_price')->first();

        $subCateList = sub_category_one::where('suco_flag','1')->orderBy('suco_name')->get();

        return view('search_product')->with(['subCateList'=>$subCateList,'pro'=>$pro,'subCate'=>$subCate,'cateInfo'=>$cate,'sysfromPrice'=>$sysfromPrice,'suppList'=>$suppList]);
    }

Frontend

{!! $pro->links() !!}


via Chebli Mohamed

mercredi 22 juin 2022

Error when trying to install Laravel Via Composer

I already have Composer and XAMPP installed. But when I try to use composer create-project laravel/laravel example-app command to create a new project by using Composer directly I throws some errors

C:\Users\HP>composer create-project laravel/laravel example-app
Creating a "laravel/laravel" project at "./example-app"
Installing laravel/laravel (v9.1.10)
  - Installing laravel/laravel (v9.1.10): Extracting archive
Created project in C:\Users\HP\example-app

In CreateProjectCommand.php line 497:

  chdir(): No such file or directory (errno 2)


create-project [-s|--stability STABILITY] [--prefer-source] [--prefer-dist] [--prefer-install PREFER-INSTALL] [--repository REPOSITORY] [--repository-url REPOSITORY-URL] [--add-repository] [--dev] [--no-dev] [--no-custom-installers] [--no-scripts] [--no-progress] [--no-secure-http] [--keep-vcs] [--remove-vcs] [--no-install] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--ask] [--] [<package> [<directory> [<version>]]]


C:\Users\HP>

I have tried:

  1. Reinstalling Composer
  2. Changing folder where I want to create my project
  3. Using the composer global require laravel/installer I'm using Composer version 2.3.7 and PHP Version 8.1.6. Im trying to install laravel 9 and my XAMPP is version 3.3.0


via Chebli Mohamed

Is The Possible Laravel Failed job Queue After Restart Not Run Begain

** is the possible laravel failed job queue after restart not run begging ? **

i am facing a problem in my laravel job service when my laravel service will be failed so, i will start again using command "retry default" so, "default" service start again but messages sent again and again from start and duplicate



via Chebli Mohamed

lundi 20 juin 2022

Google Geocoding API error with file_get_contents()

I have a code block that I've cloned from a production environment into a development environment and I'm now getting an error on the dev side that reads:

file_get_contents(): SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed

This is happening on the file_get_contents line below.

I'm unsure why this would not be working now


    $cacheKey = 'postalCodeCoordinates' . $zipcode;
    $coordinates = Cache::get($cacheKey);
    if (is_null($coordinates)) {
        $zipcode = urlencode($zipcode);

        // TODO: replace with way to let user pick country
        $country_component = isset(self::$countryZipOverrides[$zipcode]) ?
                '|country:'.self::$countryZipOverrides[$zipcode]         :
                ''                                                       ;
        $url = "https://maps.googleapis.com/maps/api/geocode/json?components=postal_code:{$zipcode}{$country_component}&sensor=false&key=" . config('services.geocoding.google.key');

        /*error is on this file_get_contents line*/
        $data = file_get_contents($url);
        $json = json_decode($data, true);
        if ($json['results']) {
            $coordinates = $json['results'][0]['geometry']['location'];
            Cache::put(
                $cacheKey,
                $coordinates,
                10080); // 1 week in minutes
            return $coordinates;
        }
    }
    return $coordinates;



via Chebli Mohamed

how to set redis laravel cookies for localhost:3338 frontend by domain server

i`m using laravel 5.6 and trying to create react frontend (redis session). my problem is: the cookies and sessions not responding to local host from server(domain) can i set localhost to domain whitelist session or another way to do that.

i changed config/session.php

[
   'lifetime' => env('SESSION_LIFETIME', 120),

   'expire_on_close' => false,

   'encrypt' => false,

   'files' => storage_path('framework/sessions'),

   'connection' => null,

   'table' => 'sessions',

   'store' => null,

   'lottery' => [2, 100],

   'cookie' => env(
       'SESSION_COOKIE',
       str_slug(env('APP_NAME', 'laravel'), '_') . '_session'
   ),

   'path' => '/',

   'domain' => env('SESSION_DOMAIN', 'localhost:3338'),

   'secure' => env('SESSION_SECURE_COOKIE', false),
   
   'http_only' => true,
   
   'same_site' => null,
]


via Chebli Mohamed

samedi 18 juin 2022

I have a problem when adding the coupon to get a discount

I tried checking many times but it always shows the message that Coupon Code is invalid!

//cart-component.blade.php

            <div class="summary">
                    <div class="order-summary">
                        <h4 class="title-box">Order Summary</h4>
                        <p class="summary-info"><span class="title">Subtotal</span><b class="index">LE</b></p>
                        @if(Session::has('coupon'))
                        <p class="summary-info"><span class="title">Discount ()</span><b class="index">LE </b></p>
                        <p class="summary-info"><span class="title">Subtotal With Discount</span><b class="index">LE </b></p>
                        <p class="summary-info"><span class="title">Tax (%)</span><b class="index">LE </b></p>
                        <p class="summary-info total-info "><span class="title">Total</span><b class="index">LE </b></p>

                        @else
                        <p class="summary-info"><span class="title">Tax</span><b class="index">LE</b></p>
                        <p class="summary-info"><span class="title">Shipping</span><b class="index">Free Shipping</b></p>
                        <p class="summary-info total-info "><span class="title">Total</span><b class="index">LE</b></p>
                        @endif

                    </div>
                    @if(!Session::has('coupon'))
                        <div class="checkout-info">
                            <label class="checkbox-field">
                                <input class="frm-input " name="have-code" id="have-code" value="1" type="checkbox" wire:model="haveCouponCode"><span>I have a Coupon code</span>
                            </label>
                            @if($haveCouponCode == 1)
                                <div class="summary-item">
                                    <form wire:submit.prevent="applyCouponCode">
                                        <h4 class="title-box">Coupon Code</h4>
                                        @if(Session::has('coupon_message'))
                                        <div class="alert alert-danger" role="danger"></div>
                                        @endif
                                        <p class="row-in-form">
                                            <label for="coupon-code"> Enter your Coupon code:</label>
                                            <input type="text" name="coupon-code" wire:model="couponCode">
                                        </p>
                                        <button type="submit" class="btn btn-small">Apply</button>
                                    </form>
                                </div>
                            @endif
                        @endif
                        <a class="btn btn-checkout" href="checkout.html">Check out</a>
                        <a class="link-to-shop" href="shop.html">Continue Shopping<i class="fa fa-arrow-circle-right" aria-hidden="true"></i></a>
                    </div>
                    <div class="update-clear">
                        <a class="btn btn-clear" href="#" wire:click.prevent="destroyAll()">Clear Shopping Cart</a>
                        <a class="btn btn-update" href="#">Update Shopping Cart</a>
                    </div>
                </div>
    

//And here is the Component class

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Sale;
use App\Models\Coupon;
use Cart;

class CartComponent extends Component
{
    public $haveCouponCode;
    public $couponCode;
    public $discount;
    public $subtotalAfterDiscount;
    public $taxAfterDiscount;
    public $totalAfterDiscount;

    public function applyCouponCode(){
        $coupon = Coupon::where('code',$this->couponCode)->where('cart_value','<=',Cart::instance('cart')->subtotal())->first();
        if(!$coupon){
            session()->flash('coupon_message','Coupon Code is invalid!');
            return;
        }
        session()->put('coupon',[
            'code' =>  $coupon->code,
            'type' =>  $coupon->type,
            'value' =>  $coupon->value,
            'cart_value' =>  $coupon->cart_value
        ]);
    }

    public function calculateDiscount(){
        if(session()->has('coupon')){
            if(session()->get()['type'] == 'fixed'){
                $this->discount = session()->get('coupon')['value'];
            }else{
                $this->discount =(Cart::instance('cart')->subtotal() * session()->get('coupon')['value'])/100;
            }
            $this->subtotalAfterDiscount = Cart::instance('cart')->subtotal - $this->discount;
            $this->taxAfterDiscount = ($this->subtotalAfterDiscount * config('cart.tax'))/100;
            $this->taxAfterDiscount = $this->subtotalAfterDiscount + $this->taxAfterDiscount;
        }
    }
    public $sale;
    public function render()
    {
        if(session()->has('coupon')){
            if(Cart::instance('cart')->subtotal() < session()->get('coupon')['cart_value']){
                session()->forget('coupon');
            }else{
                $this->calculateDiscount();
            }
        }
        $sale = Sale::find(1);
        return view('livewire.cart-component',['sale'=>$sale])->layout("layouts.base");
    }
}

//cart.php in config file This is the page responsible for the tax

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Default tax rate
    |--------------------------------------------------------------------------
    |
    | This default tax rate will be used when you make a class implement the
    | Taxable interface and use the HasTax trait.
    |
    */

    'tax' => 21,

    /*
    |--------------------------------------------------------------------------
    | Shoppingcart database settings
    |--------------------------------------------------------------------------
    |
    | Here you can set the connection that the shoppingcart should use when
    | storing and restoring a cart.
    |
    */

    'database' => [

        'connection' => null,

        'table' => 'shoppingcart',

    ],

    /*
    |--------------------------------------------------------------------------
    | Destroy the cart on user logout
    |--------------------------------------------------------------------------
    |
    | When this option is set to 'true' the cart will automatically
    | destroy all cart instances when the user logs out.
    |
    */

    'destroy_on_logout' => false,

    /*
    |--------------------------------------------------------------------------
    | Default number format
    |--------------------------------------------------------------------------
    |
    | This defaults will be used for the formated numbers if you don't
    | set them in the method call.
    |
    */

    'format' => [

        'decimals' => 2,

        'decimal_point' => '.',

        'thousand_seperator' => ','

    ],

];

What is the problem with my code? I tried many times and checked the code, but I did not find a solution



via Chebli Mohamed

vendredi 17 juin 2022

laravel method post action route is shown in red

enter image description here

The route save.appointment is shown in red I have made as per the instructions



via Chebli Mohamed

Laravel controller query

I have a laravel project with Laravel Framework 5.8.38 I try to convert mysql query:

SELECT b.name as business_location_name , u.first_name as cashier_first_name , u.last_name as cashier_last_name , cr.location_id , SUM(CASE WHEN tp.is_return = '0' AND tp.method = 'cash' THEN tp.amount ELSE 0 END) totalCash, SUM(CASE WHEN tp.is_return = '1' AND tp.method = 'cash' THEN tp.amount ELSE 0 END) totalReturn , SUM(CASE WHEN tp.is_return = '0' AND tp.method = 'card' THEN tp.amount ELSE 0 END) totalCard , cr.created_at , cr.closed_at
FROM cash_registers as cr
LEFT JOIN transaction_payments as tp ON cr.user_id = tp.created_by
LEFT JOIN users as u ON u.id = cr.user_id
LEFT JOIN business_locations as b ON b.id = cr.location_id
WHERE (tp.paid_on BETWEEN cr.created_at AND cr.closed_at) AND cr.status = "close" AND cr.created_at LIKE "2022-06-01%"
GROUP BY cr.location_id , cr.user_id
ORDER BY cr.location_id ASC, cr.user_id ASC

To lavravel query

$startDate = "2022-06-01";
   $results3 = DB::table('cash_registers as cr')
           ->select(DB::raw('b.name as business_location_name , u.first_name as cashier_first_name , u.last_name as cashier_last_name , cr.location_id , SUM(CASE WHEN tp.is_return = "0" AND tp.method = "cash" THEN tp.amount ELSE 0 END) totalCash, SUM(CASE WHEN tp.is_return = "1" AND tp.method = "cash" THEN tp.amount ELSE 0 END) totalReturn , SUM(CASE WHEN tp.is_return = "0" AND tp.method = "card" THEN tp.amount ELSE 0 END) totalCard , cr.created_at , cr.closed_at'))
           ->leftjoin('transaction_payments as tp','tp.created_by', '=', 'cr.user_id')
           ->leftjoin('users as u','u.id', '=', 'cr.user_id')
           ->leftjoin('business_locations as b','b.id', '=', 'cr.location_id')
           ->whereBetween('tp.paid_on',['cr.created_at', 'cr.closed_at'])
           ->where('cr.status', '=' , 'close')
           ->where("cr.created_at", "like", $startDate.'%')
           ->groupBy('cr.location_id')
           ->groupBy('cr.user_id')
           ->orderBy('cr.location_id', 'asc')
           ->orderBy('cr.user_id', 'asc')
           ->get();

But when I run the query on phpmyadmin ,it returns correct result , but when fire the laravel query , it returns empty array []

What's the problem ?

Thanks in advance



via Chebli Mohamed

Laravel 5.4 PHP 7.4 sometime getting JWT token decoding issue with different different exceptions and sometime its working properly

Function to generate token

function authTokenGenerator($name, $id): string
{
    $payload = [
        'iat' => time(),
        'exp' => time() + 3600,
        'nam' => $name,
        'sid' => $id,
    ];
    try {
        $token = JWT::encode($payload, env('SECRET'), 'HS256');
    } catch (Exception $exception) {
        throw $exception;
    }
    $decodeToken = JWT::decode($token, env('SECRET'), ['HS256']);
    if (!isset($decodeToken) || empty($decodeToken)) {
        $this->generateJwtToken($panNumber, $sessionId);            
    }
    return $token;
}

**Inside middle ware we are using **

$decoded = JWT::decode($request->header('token') , $key, ['HS256']);

to decode token and here we get sometimes issues.

[2022-06-16 17:58:38] local.ERROR: Signature verification failed {"exception":"[object] (Firebase\JWT\SignatureInvalidException(code: 0): Signature verification failed at vendor/firebase/php-jwt/src/JWT.php:122)

[2022-06-16 17:58:44] local.ERROR: Signature verification failed {"exception":"[object] (Firebase\JWT\SignatureInvalidException(code: 0): Signature verification failed at vendor/firebase/php-jwt/src/JWT.php:122)

[2022-06-17 16:41:37] local.ERROR: {"Issue Token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2NTU0NjQzMjUsImV4cCI6MTY1NTQ5MzEyNSwicGFuIjoiR01QUFMxMjQzTCIsInNpZCI6MzQ5MDgyOTR9.IKxOY46C_J4r_JKOkVuWQdFeFLjhIWdTGE8bI0-2kxg","Session":"34908294","Exception_Message":"Cannot handle token prior to 2022-06-17T16:42:05+0530","file":"vendor/firebase/php-jwt/src/JWT.php","Line":137}

[2022-06-17 16:41:37] local.ERROR: Cannot handle token prior to 2022-06-17T16:42:05+0530 {"exception":"[object] (Firebase\JWT\BeforeValidException(code: 0): Cannot handle token prior to 2022-06-17T16:42:05+0530 at vendor/firebase/php-jwt/src/JWT.php:137)



via Chebli Mohamed

jeudi 16 juin 2022

how to pass one data view and others view page in laravel

i have two pages file in my view first is my home blade then second is category blade and both of them using extends asidenav my problem is when im redirecting to category file it gives me a error Undefined variable: categories but in my home file when im redirecting it's working fine . i will describe my code.

in my controller HomeController i pass one data categories to home.blade.php

class HomeController extends Controller
{
    public function home()
    {
        $categories = Category::select('id','name')->get();

        return view('home', compact('categories'));
     }

     public function category(){
        return view('category');
     }
}

the output of my home.blade.php

@extends('asidenav')
@section('section')
<main>
    this is homepage
</main>
@endsection

you can see in my home blade there is a extends asidenav . inside of my asidenav extends the data categories i passed is inside of that asidenav to make a list of categories

the output of my extends asidenav where the data i pass categories

<ul>    
    @foreach($categories as $category)
        <li><a href=""><span></a>
    @endforeach
</ul>

when i click the ahref to redirect the category blade it gives the error undefined variable categories. but when im redirecting to home blade it's working the output of my category.blade.php

@extends('asidenav')
@section('section')
<main>
    this is category
</main>
@endsection

but when i tried this code in my category controller it's working fine the error of undefined variable categories not showing

   public function category()
        {
          $categories = Category::select('id','name')->get();

             return view('category', compact('categories'));
        }

my point here is i want to pass only single data categories in my home blade and others file blade like a props but i don't have a idea how to do that



via Chebli Mohamed

mercredi 15 juin 2022

$request->route() returns null in laravel

I have this code:

class TotersProviderLoginController extends Controller
{

    private $oauthService;

    public function __construct(Request $request)
    {
        $provider = $request->route()->parameter('provider'); // error here
        if($provider == 'google')
            $this->oauthService = new GoogleOauthService();
        else
            throw new \Exception('Provider '.($provider ?? '').' not supported!');
    }

I have the following routes defined:

Route::get('login/toters/{provider}', 'Accounts\TotersProviderLoginController@redirectToProvider');
Route::get('login/toters/{provider}/redirect', 'Accounts\TotersProviderLoginController@handleProviderCallback');
Route::get('login/toters/{provider}/csrf', 'Accounts\TotersProviderLoginController@getCsrf');
Route::post('login/toters/{provider}/oauth', 'Accounts\TotersProviderLoginController@requestToken');
    

for some reason when I run

php artisan route:list --verbose

I get this error

In TotersProviderLoginController.php line 38:

  [Symfony\Component\Debug\Exception\FatalThrowableError]
  Call to a member function parameter() on null

so it's clear that $request->route() is returning null. Why is that? note: I'm using Laravel 5.8



via Chebli Mohamed

mardi 14 juin 2022

How to fix when I update composer on laravel

I trying to run my laravel 5 project on laravel 8. When I am trying to update my laravel composer. I am fetching this kind of problem.

Here the problem is



via Chebli Mohamed

lundi 13 juin 2022

Laravel Undefined variable $

I'm getting this error:

Undefined variable $nilais

This is the code from my main.blade.php

<tbody>
            @foreach ($nilais as $nilai)
            <tr>
                <td class="text-center" scope="row"></td>
                <td></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center"></td>
                <td class="text-center">Lulus</td>
                <td class="text-center">
                    <button type="button" class="btn btn-warning"> Edit </button>
                    <button type="button" class="btn btn-danger"> Hapus </button>
                </td>
            </tr>
            @endforeach

my Controller

class MainController extends Controller
{
    public function index(){
        $nilais = Nilai::get();
        return view('main', compact('nilais'));
    }}

and this is the route

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

I don't know what is wrong, please help.

I'm aware there are other questions like this, but I already tried the solutions, and nothings work.

Thank you so much.



via Chebli Mohamed

dimanche 12 juin 2022

How can i Redirect Laravel 7 Bulk Old URL to New URL ? 4000+ Old URLs to New

I want to redirect my Old URL to New URL

OLD URL : http://example.com/productsite-reviews

New URL : http://example.com/reviews/productsite.com

The problem is i have more than 4000+ URLS. Can we redirect the old URL to New URL without .htaccess file ?

this is my home route

Route::get('/', 'HomeController')->name( 'home' );

Is there any way to redirect these URL in bulk without writing htaccess code?



via Chebli Mohamed

Laravel force http to https redirect but caused "too many redirects"

I have a Saas product which allows my end-user to bind their own domain to manage their products but I encountered an issue when I try to redirect those requests that is originally not requested by "http" to "https", the site will return "too many request redirection". Meanwhile, I do not want to configure port 443 into my nginx configuration as some of scenario, some of the request path might not need to neccessary to have "https". If I configured the force redirection in nginx which means all the request must served under "https" which might leads all of the request path is served via "https" but what I want to achieve is only some of the request path served under https only.

Below is the code that used to achieve the force redirection from http to https

 if (!$request->secure()) {
            return redirect()->secure($request->path());
        }


via Chebli Mohamed

jeudi 9 juin 2022

Can not access a image file in controller using jquery in laravel

I am trying to catch all data to controller using jquery in laravel. Except image file, i caught all the data in controller and i tried lots of code but did not success. In the below i gave controller and view code of laravel.

View:

<form action="" method="post" enctype="multipart/form-data" id="forms">
@csrf
<div class="row">
    <div class="col-md-4"> 
        <label>Profile Picture</label>
        <input class="form-control" type="file" name="file" id="file">
    </div>
</div>
<div>
    <button type="submit" id="submit">Submit</button>
</div>
</form>
<script>
    $(function(){        
    $("#forms").on('submit', function(e){
        e.preventDefault();
        $.ajax({
            url:$(this).attr('action'),
            method:$(this).attr('method'),
            data:new FormData(this),
            processData:false,
            dataType:'json',
            contentType:false,
            success:function(data){
                console.log(data);
                
            }
        });
    });
});
</script>

Controller:

public function store(Request $request){
    return $request->all();  
}

and also i tried this code:

public function store(Request $request){
    return $request->file('file');  
}

i failed to catch the image file in my controller using javascript. please help if anyone can. Thank you



via Chebli Mohamed

How to use laravel group concat

I have a pivot table for property, client and agent

...

public static function client_property_list($id)
{
    $client_property_list = DB::table('agent_client_property as acp')
        ->leftJoin('clients as c', 'acp.client_id', '=', 'c.id')
        ->leftJoin('properties as p', 'p.id', '=', 'acp.property_id')
        ->leftJoin('agents as a', 'a.id', '=', 'acp.agent_id')
        ->select(DB::raw('p.*'))
        ->where('c.id','=',$id)
        ->get();

    return $client_property_list;
} 

...

one property can have multiple agents, i want to group those agents to show only 1 on the list

tried this didnt worked

public static function client_property_list($id)
    {
        $client_property_list = DB::table('agent_client_property as acp')
            ->leftJoin('clients as c', 'acp.client_id', '=', 'c.id')
            ->leftJoin('properties as p', 'p.id', '=', 'acp.property_id')
            ->leftJoin('agents as a', 'a.id', '=', 'acp.agent_id')
            ->select(DB::raw('p.*,a.first_name as name'))('group_concat(name) as names')
            ->where('c.id','=',$id)
            ->whereNull('c.deleted_at')
            ->whereNull('p.deleted_at')
            ->whereNull('a.deleted_at')
            ->get();

        return $client_property_list;
    } 


via Chebli Mohamed

mercredi 8 juin 2022

View [views.create] not found [closed]

I do not even know what should I do more?

this is my web.php

use App\Http\Controllers\HomeController;

 Route::get('/home', [HomeController::class,'index']); // have another version no worry

This is controller:

class HomeController extends Controller
{

    public function index()
{
    //
    return view('views.create');
}

this is view:

create.blade.php  // in views folder

sdhfbskdfnkds

What did I miss? Why does appear this error? I did lots of things:

composer update
php artisan config:cache
php artisan cache:clear
checked folders - views, sessions,cache in storage
re installed laravel 


via Chebli Mohamed

Unable to fetch results from hasManyJson Using staudenmeir / eloquent-json-relations

I have been working on two tables Category & Product. In Category Model I have a relationship like

class Category extends Model
{
  use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
  public function products(){

    return $this->hasManyJson(Product::class,'category_ids[]->id');
  }
}

In Products Model I have a relationship like

class Product extends Model
    {
      use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
      protected $casts = [
          'category_ids'=>'json', 
      ];
      public function products(){

        return $this->belongsToJson(Category::class,'category_ids[]->id');
      }
    }

Now in my controller when I'm doing trying to get count of each categories product, it is giving me Empty results, below is my controller code.

public function two_category()
{
    $list = Category::where('home_status', true)->get();
    foreach($list as $ls){
        echo $ls->name.'    '.count($ls->products).'<br>';
    }
    dd('ended');
   }

This is giving -

Category1 0

Category2 0

And finally this is how my column in product table looks like. Category id column in json



via Chebli Mohamed

mardi 7 juin 2022

Can not set columns of db table in Laravel Php

I am new to laravel. I have three tables in my DB

  1. dsp_account with fields id,name_display,short_name.

enter image description here

  1. dsp with fields id,dsp_account_id.

enter image description here.

  1. rtbcfg_region_dsp with fields dsp_id,status.

enter image description here.

dsp table connected to dsp_account table via dsp_account_id field.

dsp table connected to rtbcfg_region_dsp via dsp_id.

I try to create this sql query:

select distinct dsp_account.id,dsp_account.name_display,dsp_account.short_name
from dsp_account
inner join dsp on dsp.dsp_account_id = dsp_account.id
AND dsp.id 
IN(SELECT dsp_id
FROM rtbcfg_region_dsp
group by dsp_id, status
having count(*)>0 and status = 1) order by dsp_account.name_display ASC;

this is my code:

$all_list6 = DspAccount::select('DspAccount.id', 'DspAccount.name_display','DspAccount.short_name')
            ->join('dsp', 'dsp.dsp_account_id', '=', 'dspAccount.id')
            ->whereIn('DSP.id',function($query)
            {
                $query->select('dsp_id')
                ->from('rtbcfg_region_dsp')
                ->groupBy('dsp_id','status')
                ->havingRaw('COUNT(*) > 0 AND status = 1');
        
            })
            ->get();

this is the error that I got: what I am missing:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'DspAccount.id' in 'field list' (SQL: select `DspAccount`.`id`, `DspAccount`.`name_display`, `DspAccount`.`short_name` from `dsp_account` inner join `dsp` on `dsp`.`dsp_account_id` = `dspAccount`.`id` where `DSP`.`id` in (select `dsp_id` from `rtbcfg_region_dsp` group by `dsp_id`, `status` having COUNT(*) > 0 AND status = 1) and `dsp_account`.`deleted_at` is null) 

enter image description here



via Chebli Mohamed

lundi 6 juin 2022

Laravel Job Withcount Parameter not Accessible in job Laravel 5.6

Hii I created a job to send mail. I execute a query in the controller using withCount() and am able to get the count parameter inside the controller but while I am parsing the same data to the job and assign to a local variable in constructer then I use a local variable inside the handle method count parameter was missing in my local.

I am using SYNC as QUEUE_DRIVER and code files below mention

Controller

 $confernceIterationData = ConferenceIteration::with('AbstractNews')->withCount('AbstractNews')->where('id', $unserializeData['confid'])->first();
              
 $this->dispatch(new SendtronAutomatedEmailJob($confernceIterationData, $unserializeData, $attachments));

Controller Output of dd($confereceIterationData)

array:42 [
    "id" => 9085
    "conference_iteration_id" => "e3f65fda-7776-4e64-82d8-b5f1289141e2"
    "conference_id" => 259
    "name" => "American Association of Cancer Research Annual Meeting 2022"
    "acronym" => "AACR 2022"
    "abstract_news_count" => 8339
  ]

Job

<?php

namespace App\Jobs;

use App\Mail\SendTronAutomatedMail;
use App\TeamConferences;
use App\User;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

class SendtronAutomatedEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * conference Iteration data
     *
     * @var object
     */
    protected $confrenceData;

    /**
     * Planner Form Data
     *
     * @var array
     */
    private $formData;

    /**
     * attchement files
     *
     * @var array
     */
    private $files;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($confrenceData, $formData, $files)
    {
        $this->confrenceData = $confrenceData;
        $this->confrenceData->abcount = $confrenceData->abstract_news_count;
        $this->formData = $formData;
        $this->files = $files;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        dd($this->confrenceData);

        $request = $this->formData;
        $i = 0;
        $users = User::select('email')->distinct()->wherehas('teams', function ($q) use ($request) {
            $q->whereIn('id', $request['teams']);
        })->pluck('email')->toarray();

        $subject = $this->confrenceData->acronym . " Conference Planner (" . $this->confrenceData->data_status . ")";

        

        $this->extractConfenceData($this->confrenceData);

      
 
        // dd($this->confrenceData->AbstractNews_count);

        $count = count($users);
        foreach ($users as $user) {
            Log::channel('sendtron_email')->info('Authomated Mail Send To .', ['id' => $user]);

            Mail::to($user)->send(new SendTronAutomatedMail($request['content'], $subject, $this->files));
            if (++$i === $count) {
                unset($users);
                TeamConferences::where('conference_iteration_id', $request['confid'])->whereIn('team_id', $request['teams'])->update(['last_mail_sent' => Carbon::now()->toDateTimeString()]);
                Storage::disk('s3SendTron')->delete(array_column($this->files, 's3path'));
            }
        }

    }
}

If we dd($confrenceData) in constructor we get the attribute abstract_news_count as mention in controller output.

but at the same time if we dd($this->confrenceData) we unable to get abstract_news_count



via Chebli Mohamed

laravel old env file is downloading while mywebsite/.env in shared hosting in laravel 5.6 in production mode

I am using laravel 5.6 in my shared hosting website. my project .env file is downloading while mywebsite/.env in production mode. The old env file is downloading means I was changed the env file content but downloading the old env file which is not available in my project. I have use the below code in .htacceses but still downloading <Files .env> order allow,deny Deny from all



via Chebli Mohamed

dimanche 5 juin 2022

image not display in admin panel

Image not display why in laravel, what is the issue controller nd blade is added Controller code

 try{

      $file=$request->file('image');
      $filename=$file->getClientOriginalName();
      $imgname = uniqid().$filename;

      $input['image']= $imgname;
      $destinationPath=public_path('upload/image/');
      $request->file('image')->move($destinationPath, $imgname);

  
        Auth::user();
        $article =  new Article();
        $article -> user_id=Auth::user()->id;
        $article -> title=$request->get('title');
        $article -> description=$request->get('description');
        $article-> image = $filename;
        $article -> status=$request->get('status');
        $article->save();
    $request->session()->flash('alert-success','article has been sucessfully created.');
    return back()->with('success', 'Article created successfully.');   
    }
catch(ModelNotFoundException $exception){
   // do task when error
    return back()->withError($exception->getMessage())->withInput();    }

}

in blade file print this code

 <td><img src=""
                                            width="500px"></td>


via Chebli Mohamed

jeudi 2 juin 2022

Laravel how to count each rows ID on tables relationship

so i have a 5 tables in my database with pivot, Countries, Cities, Shops, Users, shop_employee their relationship is this

Countries  | Cities      | Shops     | shop_employees| Users 
 id        | country_id  | city_id   |  shop_id      | id
                                        employee_id

my goal is i want to count each City, shop, employees in Country

this is my controller

class CountryController extends Controller
{
    public function country(){
       $countries = Country::with(['cities.shops.employees'])->get();
       return view('country',['countries'=>$countries]);
    }
}

this is my model Country

class Country extends Model
{
    public function cities(){
        return $this->hasMany(City::class);
    }
}

this is my model City

class City extends Model
{
    public function shops(){
        return $this->hasMany(Shop::class);
    }
}

this is my model Shops

class Shop extends Model
{
    public function employees(){
        return $this->belongsToMany(User::class,'shop_employees','shop_id','employee_id');
    }
}

this is my view

        <table class="table-fixed">
                <thead>
                  <tr>
                    <th class="py-2 px-2 border border-gray-300">Country</th>
                    <th class="py-2 px-2 border border-gray-300">City</th>
                    <th class="py-2 px-2 border border-gray-300">Shop</th>
                  </tr>
                </thead>
                <tbody>
                @foreach ($countries as $country)
                <tr >
                    <td class="py-2 px-2 border border-gray-300"></td>
                    <td class="py-2 px-2 border border-gray-300"></td>
                    <td class="py-2 px-2 border border-gray-300"></td>
                  </tr>
                @endforeach
                </tbody>
              </table>

i tried this code its working fine the City is counting


the output, in this output i want to display the count of shops and employee

enter image description here

but when im trying this code it gives me a error

  $country->cities->shops->count() or
  $country->cities->shops->employees->count() 

error: Property [shops] does not exist on this collection instance



via Chebli Mohamed

How to save multiple array input data in Database in Laravel PHP

Hello Geeks i am stuck here. I am beginner and want to know how to save and update array data in database. this is laravel form requested data

I want to save data like this : mysql database

here is my form request, i want to save data in mysql database, with new row :

"_token" => "FoyoYvFXmNAggbQuMq6PN243QS43MkY99Nq3UAni"
"description" => array:2 [▼
 0 => "<h3>Shared Hosting Plan</h3>"
 1 => "<h3>Cloud Hosting Plan</h3>"
]
"site_id" => array:2 [▼
 0 => "5361"
 1 => "5361"
]
"category_id" => array:2 [▼
 0 => "1"
 1 => "3"
]
"field_1" => array:2 [▶]
"field_2" => array:2 [▶]
"field_3" => array:2 [▶]
"field_4" => array:2 [▶]
"field_5" => array:1 [▶]
"price" => array:2 [▶]
"update_plan" => "Save Plans"
]```




via Chebli Mohamed

mercredi 1 juin 2022

How to fetch mobile contacts in laravel?

I am using laravel framework to develop mobile application ,i have one blocker how to fetch contacts from device by using laravel api,can anyone give me suggestions how to achieve this one..?



via Chebli Mohamed

cant seem to change my url to tally with my lavarel app

So what I am trying in my mac hosts file is:

127.0.0.1 firstproject.test

But when I run the local server and hit firstproject.test nothing happens. I was expecting that URL to resolve to 127.0.0.1?

using php artisan serve



via Chebli Mohamed