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

dimanche 30 octobre 2022

Dynamic Scopes not working properly when dealing with tags->products() (many to many relationship) Laravel Livewire

its throwing me this error:

Call to a member function products() on null

i want the filter to be changed in real time and it works too just not working properly with many to many relationship:

this doesnt work

$tag1 =  request()->query('tag');  
$tag = Tag::where('name', $tag1)->first();
$products = $tag->products()->SortFilterBy($this->sortBy)->InStock()->paginate($this->perPage);

but when i manually type this

$products = $tag->products()->SortFilterBy('featured')->InStock()->paginate($this->perPage); //
Works But not in real time
$products = Product::SortFilterBy($this->sortBy)->InStock()->paginate($this->perPage); //WORKS IN REAL TIME

i am using livewire for this.

The Scope:


public function scopeSortFilterBy($query,$sortBy = "")
{
switch ($sortBy) {
case 'featured':

                return $query->where('featured','=', -1);
    
                break;
    
            case 'low':
           
                return $query->orderBy('sale_price', 'asc');
               
                break;
            case 'heigh':
                return $query->orderBy('sale_price', 'desc');
                break;
            default:
    
            return $query;
            
            break;
        }
      
    }

it do shows me the value of dd($this->sortBy) whenever i change the dropdown.



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

I want to pull mysql export text from laravel

I want to pull mysql export text from laravel

INSERT INTO 'example' ('id', 'name') VALUES (1, 'example'), 
(2, 'example2'),
(3, 'example3'),
(4, 'example4');

Like this

Thank you.

I searched for sql query but couldn't find it



via Chebli Mohamed

dimanche 23 octobre 2022

Can't seem to find a way to use the route.php from 5.2 from laravel 5.2 to 8.83.25 web.php

I'm pretty new with Laravel, was able to work on finding a tutorial but it uses a 5.2 version.

I'm trying to convert the older version to 8.83.25

This is the route in the tutorial that I'm following. I have created the CategoryController.php manually

Route::group(['middleware' => ['web']], function(){
    Route::get('category', 'CategoryController');
});

enter image description here



via Chebli Mohamed

samedi 22 octobre 2022

Laravel Trying to get property of non-object $-> non Object

    public function handle()
    {
        $response = json_decode(file_get_contents(config('app.vatusa_api_base') . '/facility/zdv/roster?apikey=' . config('app.vatusa_api_key')));

        // Create Users

        foreach ($response as $user) {
            if(!User::where('vatsim_id', $user->cid)->whereNull('home_facility')->count()) {
                switch($user->rating) {
                    case 12:
                        $rating = 'ADM';
                        break;

Attempting to Pull from Our API For a Roster though it seems that I have messed something up somewhere.

Any and all help is appreciated.



via Chebli Mohamed

vendredi 21 octobre 2022

Laravel Update from 4.2 to 5.6

I'm getting the following error when running composer install:

PHP Fatal error: Uncaught ReflectionException: Class App\Console\Kernel does not exist in /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php:788 Stack trace: #0 /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php(788): ReflectionClass->__construct('App\Console\Ker...') #1 /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php(667): Illuminate\Container\Container->build('App\Console\Ker...') #2 /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php(265): Illuminate\Container\Container->resolve('App\Console\Ker...', Array, false) #3 /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php(785): Illuminate\Container\Container->Illuminate\Container{closure}(Object(Illuminate\Foundation\Application), Array) #4 /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php(667): Illuminate\Container\Container- in /home/ubuntu/fusion/laravel/vendor/laravel/framework/src/Illuminate/Container/Container.php on line 788

This is what I have in my composer.json

    "require": {
            "php": "^7.1.3",
            "fideloper/proxy": "^4.0",
            "laravel/framework": "5.8.*",
            "laravel/tinker": "^1.0"
        },
        "require-dev": {
            "filp/whoops": "^2.0",
            "fzaninotto/faker": "^1.4",
            "mockery/mockery": "^1.0",
            "nunomaduro/collision": "^2.0",
            "phpunit/phpunit": "^7.0"
        }

Thanks!



via Chebli Mohamed

jeudi 20 octobre 2022

Laravel instantiating $response takes abnormally long

I have a Laravel 5.8 application, with very long loading times. Laravel’s speed is debugable within the public/index.php file. Which I have tried like this:

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

dd(microtime(true) - LARAVEL_START); 

Between LARAVEL_START being set, and the response being sent, it will take a staggering six to fourteen seconds to load. Switching my code to:

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

dd(microtime(true) - LARAVEL_START);    

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

Will yield an average loading time of about 0.6 to 2 seconds between Laravel booting and $kernel being set. This means that loading the kernel takes an average of 1.2 seconds, and processing the request takes about 11-13 seconds. Now, what I have tried to speed up the fetching of a page so far:

Dumping cache

Most Laravel problems are usually solved by clearing the cache, running php artisan optimize, dumping composer autoload, etc. This didn't yield any time difference.

Reinstalling the project

I tried to reinstall the project from it's GitHub repository, which also had no impact on the loading times. I rebuild the docker container from scratch as well, more about docker in the next paragraph

Docker

As I have been doing a lot of research into why my Laravel application could be slow, I stumbled upon many articles stating that docker could slow down Laravel substantially. To combat this, I’ve tried the following:

PHP artisan serve, instead of using docker, I’ve tried to use the built in webserver. This does not speed up the application.

  • I switched between a few PHP 7.X versions, to no avail.
  • My other projects work fine with the artisan serve command. Loading times are somewhere around 20-200 milliseconds.

Xampp, does not speed up the executable time.

  • My other projects work fine with xampp. Loading times are around 20-300 milliseconds.

Controller debugging

As I have eliminated the possibility of my webserver being the bottleneck, I timed the difference between the first and last line of my controller like this:

public function index() 
{
    $time_start = microtime(true)
    // controller code (about 40 lines)
    dd($time_end - $time_start)
}

This yields the following results:

0.31205701828003
0.24561214447021
0.23838305473328
0.12146878242493
0.25613188743591
0.30584192276001

While these seem like respectable times, my application didn’t take the average time of 0.22 seconds to boot, but rather took the expected eight to twenty seconds to boot. I tried it once again, now with a fully empty controller like this:

public function index() 
{
    $time_start = microtime(true)
    dd($time_end - $time_start)
}

Which yields an average controller execute time of 0.0 seconds. While remaining as slow as before.

Middleware

My next thought would be to debug the middlewares my project uses. As it is an enterprise application, there is a lot of validation going on under the hood, which is run before every request gets to a controller. I started off by completely removing all middlewares from the routes/web.php file. Rerunning my application does not yield any time difference. With no middleware being run, I can conclude that my slow loading times aren't due to a unoptimized middleware.

Service providers

Just like the middleware, service providers run on every request. Removing all non-essential service providers in config/app.php yields no loading time difference.

Where to go from here?

My routes/web.php now looks like:

<?php

use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| 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('/greeting', function () {
    return 'Hello World';
});

It still takes 12 seconds to load. It seems as though something is slowing down:

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

Yet, removing practically the entire project has close to zero effect on the projects speed. How can I speed up this essential project?



via Chebli Mohamed

Cannot move image/files temp to public directory Laravel 9

I am trying to upload image in Laravel. Getting following error:

enter image description here

My code is given below:

public function uploadImage($image, $image_path)
{
    $path = config('global.' . $image_path . '_image_path');

    file_exists($image) && unlink($image);

    $image_name = 'bvend-' . $image_path . '-' . time() . '.' . $image->getClientOriginalExtension();

    $image->move($path, $image_name); // $path: public_path('uploads/products')
    return $image_name;
}

I understand its a simple issue but still no clue where it causing issue.



via Chebli Mohamed

after updating PHP to 7.4 my BarcodeGeneratorHTML crashed | Laravel,PHP

i used to use my Laravel Project with PhP 5.6 and i'm using barcode Gnerator for my project some where and to do this i use this package .

laravel/laravel barcode_blog

now i upgraded my PhP To 7.4 (note: didn't upgrade my laravel yet). everything is working fine just when i search for a spasific barcode i got this error :

ErrorException in BarcodeGenerator.php line 293: 
Array and string offset access syntax with curly braces is deprecated (View:.../.../..)

now this is the code :

<tr>
    <td width="19%">serial NUM</td>
    <td style="width: 1%">:</td>
    <td colspan="2">
     @if (!empty($INSTANCE))
       <?php $generator = new \Picqer\Barcode\BarcodeGeneratorHTML(); ?>
       {!! $generator->getBarcode($INSTANCE->barcode, $generator::TYPE_CODE_128) !!}
    @endif
    </td>
   </tr>

And I know the problem is with $generator = new \Picqer\Barcode\BarcodeGeneratorHTML(); this line when i delete it my code is working fine but i need it in the code how to use it in php 7.4 i belive it get changed



via Chebli Mohamed

mercredi 19 octobre 2022

Convert Raw Sql to laravel Query buider format

I have a raw query which works correctly.

SELECT a.date_demande,a.row, a.nom,a.prenom,a.timestamp_statut,a.timestamp_statut_fmt,a.dossier_id_rapproche,a.type_enquete,
a.enquete_statut,a.code_couleur,a.code,a.type_demande_libelle, a.type_demande_couleur,a.type_demande_code,a.type_demande_icone,a.type_demande_contester,
a.type_demande_contester,a.date_demande_origin,a.date_demande,a.dossier_id, a.prestataire_equipe, a.ref_client, a.client,a.standalone,a.demandeur,
a.lieu_naissance,a.lieu_deces,a.no_boite_lettre,a.cp,a.ville,b.Phone FROM
(select
  distinct `dossiers`.`id`,
  `dossiers`.`id` as `row`,
  `nom`.`originalValue` as `nom`,
  `prenom`.`originalValue` as `prenom`,
  `dossiers`.`timestamp_statut` as `timestamp_statut`,
  DATE_FORMAT(timestamp_statut, "%d/%m/%Y") AS timestamp_statut_fmt,
  `dossiers`.`dossier_id_rapproche` as `dossier_id_rapproche`,
  CONCAT(t1.type_enquete, ' - ', t1.lib_type_enquete) as type_enquete,
  `enquete_statuts`.`libelle` as `enquete_statut`,
  `enquete_statuts`.`code_couleur` as `code_couleur`,
  `enquete_statuts`.`code` as `code`,
  `type_demande_client`.`libelle` as `type_demande_libelle`,
  `type_demande_client`.`code_couleur` as `type_demande_couleur`,
  `type_demande_client`.`code` as `type_demande_code`,
  `type_demande_client`.`icone` as `type_demande_icone`,
  `type_demande_client`.`contester` as `type_demande_contester`,
  `date_demande` as `date_demande_origin`,
  DATE_FORMAT(date_demande, "%d/%m/%Y") AS date_demande,
  `affectation`.dossier_id AS dossier_id ,
  `affectation`.prestataire_equipe AS prestataire_equipe ,
  `ref_client`,
  `clients`.`nom_raison_sociale` as `client`,
  `clients`.`standalone` as `standalone`,
  `clients`.`demandeur` as `demandeur`,
  CONCAT(t2.type_enquete, ' - ', t2.lib_type_enquete) as `type_enquete_retrouve`,
  (
    CASE
      WHEN date_de_naissance.originalValue not like "%/%/%" THEN DATE_FORMAT(`date_de_naissance`.`originalValue`, "%d/%m/%Y")
      ELSE date_de_naissance.originalValue
    END
  ) AS date_naissance,
  `lieu_de_naissance`.`originalValue` as `lieu_naissance`,
  (
    CASE
      WHEN date_de_deces.originalValue not like "%/%/%" THEN DATE_FORMAT(`date_de_deces`.`originalValue`, "%d/%m/%Y")
      ELSE date_de_deces.originalValue
    END
  ) AS date_deces,
  `lieu_de_deces`.`originalValue` as `lieu_deces`,
   `adresse_bp`.`originalValue` as `no_boite_lettre`,
  (
    CASE
      WHEN code_postal_particulier.originalValue is not null
      AND ville_particulier.originalValue is not null THEN code_postal_particulier.originalValue
      WHEN code_postal_professionnel.originalValue is not null
      AND ville_professionnel.originalValue is not null THEN code_postal_professionnel.originalValue
      ELSE code_postal_particulier.originalValue
    END
  ) as cp,
  (
    CASE
      WHEN code_postal_particulier.originalValue is not null
      AND ville_particulier.originalValue is not null THEN ville_particulier.originalValue
      WHEN code_postal_professionnel.originalValue is not null
      AND ville_professionnel.originalValue is not null THEN ville_professionnel.originalValue
      ELSE ville_particulier.originalValue
    END
  ) as ville
from
  `dossiers`
  left join `index_dossiers` as `nom` on `dossiers`.`id` = `nom`.`dossier_id`
  and `nom`.`zone` = 'etat_civil.nom'
  left join `index_dossiers` as `prenom` on `dossiers`.`id` = `prenom`.`dossier_id`
  and `prenom`.`zone` = 'etat_civil.prenom'
  left join `index_dossiers` as `date_de_naissance` on `dossiers`.`id` = `date_de_naissance`.`dossier_id`
  and `date_de_naissance`.`zone` = 'etat_civil.date_naissance'
  left join `index_dossiers` as `lieu_de_naissance` on `dossiers`.`id` = `lieu_de_naissance`.`dossier_id`
  and `lieu_de_naissance`.`zone` = 'etat_civil.lieu_naissance'
  left join `index_dossiers` as `date_de_deces` on `dossiers`.`id` = `date_de_deces`.`dossier_id`
  and `date_de_deces`.`zone` = 'etat_civil.date_deces'
  left join `index_dossiers` as `lieu_de_deces` on `dossiers`.`id` = `lieu_de_deces`.`dossier_id`
  and `lieu_de_deces`.`zone` = 'etat_civil.lieu_deces'
  left join `index_dossiers` as `code_postal_particulier` on `dossiers`.`id` = `code_postal_particulier`.`dossier_id`
  and `code_postal_particulier`.`zone` = 'adresses.particulier_cp'
  left join `index_dossiers` as `code_postal_professionnel` on `dossiers`.`id` = `code_postal_professionnel`.`dossier_id`
  and `code_postal_professionnel`.`zone` = 'adresses.professionnel_cp'
  left join `index_dossiers` as `ville_particulier` on `dossiers`.`id` = `ville_particulier`.`dossier_id`
  and `ville_particulier`.`zone` = 'adresses.particulier_ville'
  left join `index_dossiers` as `ville_professionnel` on `dossiers`.`id` = `ville_professionnel`.`dossier_id`
  and `ville_professionnel`.`zone` = 'adresses.professionnel_ville'
   left join `index_dossiers` as `adresse_bp` on `dossiers`.`id` = `adresse_bp`.`dossier_id`
  and `adresse_bp`.`zone` = 'adresses.particulier_no_boite_lettre'
   left join `index_dossiers` as `telephone` on `dossiers`.`id` = `telephone`.`dossier_id`
  and `telephone`.`zone` = 'telephones.numtel'
  inner join `entites` as `e1` on `dossiers`.`entite_id` = `e1`.`id`
  inner join `clients` on `clients`.`entite_id` = `e1`.`id`
  left join `enquete_statuts` on `dossiers`.`enquete_statut_id` = `enquete_statuts`.`id`
  left join `type_demande_client` on `dossiers`.`type_demande_client_id` = `type_demande_client`.`id`
  inner join `type_enquetes` as `t1` on `dossiers`.`type_enquete_id` = `t1`.`id`
  left join `type_enquetes` as `t2` on `dossiers`.`type_enquete_id_retrouve` = `t2`.`id`
  left join `sous_enquetes` as `se` on `dossiers`.`id` = `se`.`dossier_id`
  left join `affectation_dossiers` on `se`.`id` = `affectation_dossiers`.`sous_enquete_id`
  left join (
    SELECT
      sous_enquetes.dossier_id,
      GROUP_CONCAT(
        case
          when users.name IS NOT NULL then users.name
          ELSE case
            when equipes.libelle IS NOT NULL then equipes.libelle
            when prestataires.nom_raison_sociale IS NOT NULL then prestataires.nom_raison_sociale
          End
        END
      ) AS prestataire_equipe
    FROM
      affectation_dossiers
      JOIN sous_enquetes ON affectation_dossiers.sous_enquete_id = sous_enquetes.id
      LEFT JOIN users ON affectation_dossiers.user_id = users.id
      LEFT JOIN entites AS e ON affectation_dossiers.entite_id = e.id
      LEFT JOIN equipes ON e.id = equipes.entite_id
      LEFT JOIN prestataires ON e.id = prestataires.entite_id
    GROUP BY
      sous_enquetes.dossier_id
  ) AS affectation on `dossiers`.`id` = `affectation`.`dossier_id`
where
  `date_demande` is not NULL) AS a
  
  INNER JOIN
  
(  SELECT 
    `dossier_id`,
    GROUP_CONCAT(`originalValue`) AS `Phone`
FROM `index_dossiers`
WHERE zone = 'telephones.numtel'
GROUP BY `dossier_id`) AS b

ON a.row = b.dossier_id

I am able to write each part of the query which returns a and b seperately as query builder. I am however unable to get both to work together.

Any help or tips would be appreciated. I have tried using some online tools but to no avail I can run the query with DB::select(DB:raw('query') to get the correct results. However the results are returned as an array. The expected output is an instance of query builder for further filtering.



via Chebli Mohamed

Call to undefined function Collective\Html\is_iterable()

`(2/2) ErrorException Call to undefined function Collective\Html\is_iterable() (View: /home/finocoin/public_html/mocktest/Themes/themeone/views/exams/quiz/update-questions.blade.php)

in FormBuilder.php (line 741) at CompilerEngine->handleViewException(object(FatalThrowableError), 1) in PhpEngine.php (line 47)`



via Chebli Mohamed

lundi 17 octobre 2022

Validating filename of uploaded file in Laravel 5.4

How can I validate the filename of uploaded image file?

The scenario is:

When a user upload an image the filename must its id, if not then it will throw an message that the filename must the user id.

This is my code:

    $validation = Validator::make($request->all(), [
            'documenttosubmit' => 'required|array',
            'datesubmitted' => 'required|array',
            'file' => 'array',
            'file.*' => 'mimetypes:' . implode(",", $allowedMimes) . '|max:' . (AppDocSubmitted::MAX_FILE_SIZE * 1024), 
        ], [
            'file.*.mimetypes' => 'File must be an image (jpg/jpeg/png) or a document (pdf).',
            'file.*.max' => 'File size must be less than the maximum size of ' . AppDocSubmitted::MAX_FILE_SIZE . 'MB',
        ]);


via Chebli Mohamed

Laravel 9 - How to validate user with sanctum in Request

I have a route with the sanctum middleware, the idea of ​​this route is that only those users with a token can access it.

If I make a call with a correct token, the method works, if I try to make the query with an INVALID token, it returns an error that I can't control.

What I try by code is that if the token is not valid, it returns a 401 (unauthorized)

Route

Route::middleware('auth:sanctum')->post('cars', [CarsController::class, 'videoStore'])
    ->name('api.cars.store');

Request

 /** 
 * @param CarStoreRequest $request
 * @return Application|ResponseFactory|\Illuminate\Http\Response
 */
 public function carStore (CarStoreRequest $request)
 {

     $user = Auth::user();

     if ($user === null) {
         return response('Unauthorized', Response::HTTP_UNAUTHORIZED);
    }
 }

API action

<?php

namespace App\Http\Requests\V1;

use Illuminate\Foundation\Http\FormRequest;

class CarStoreRequest 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 [
            'image' => 'required|mimes:jpeg,jpg|max:30000',
        ];
    }
}

This is the error received with 401 http status code.

{
    "message": "",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
    "file": "C:\\xampp\\htdocs\\test-api\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Application.php",
    "line": 1151,
    "trace": [
        {
            "file": "C:\\xampp\\htdocs\\test-api\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\helpers.php",
            "line": 45,
            "function": "abort",
            "class": "Illuminate\\Foundation\\Application",
            "type": "->"
        },
        {
            "file": "C:\\xampp\\htdocs\\test-api\\app\\Exceptions\\Handler.php",
            "line": 56,
            "function": "abort"
        },


via Chebli Mohamed

why .env file configuration in laravel is not working it can't work

$this->ketnoi = mysqli_connect($_ENV['DB_HOST'], $_ENV['DB_USERNAME'], $_ENV['DB_PASSWORD'], $_ENV['DB_DATABASE']) or die('Error => DATABASE');



via Chebli Mohamed

dimanche 16 octobre 2022

Weird error when trying to send MAIL Laravel. Address in mailbox given [] does not comply with RFC 2822, 3.6.2

So i'm trying to send an email to a fixed email address

Here is the code :

        //This piece of code is executed when i press a button inside an HTML form
        $announcement = $request->input("announcement");     //This comes from an HTML text input
        $subject = "Hello this is the title of the email";
        $data = [
                'email_body' => "This is the body of the email where the message is displayed : <br><br>".$announcement
        ];

        Mail::send('emails.email_view', $data, function ($message) use ($subject) {
                $message->from(env("MAIL_FROM_ADDRESS"), 'Some name');
                $message->to("validEmail@gmail.com")->subject($subject);
        });

When this piece of code is executed it shows me the error mentioned in the title :

Address in mailbox given [] does not comply with RFC 2822, 3.6.2.

The thing is when i refresh the page(url) where the error is displayed it obviously prompts me to Confirm Form Resubmission and when i confirm, the code is executed without a problem , sending the email as it is supposed to do in the first place.

I've tried storing the email in a variable and using trim() or str_replace() to clear the string from possible whitespace, i've tried sending it inside the to() function as an array as mentioned in a question about the same problem still no luck.

Also the code 1 out of 40 tries doesn't display the error and works as supposed to work.

Im' using laravel 5.5

I'm so lost what should i do, where should i look ?



via Chebli Mohamed

samedi 15 octobre 2022

Send notification to creator on the basis of post page views in laravel?

I want to send the notification to the post creator on the basis of page views in laravel. Like when the post gets 1000 views, the creator should get a congratulatory notification. Here the problem is I am using cookies(2 hours) to prevent multiple page views. so the creator gets multiple notifications until views are moved to 1001.

if($views == 1000){
        $user = User::find($userid);
        $notificationdetails = [
          'subject' => 'Congratulations, You got your first '.$views. ' views on your new snippet - '.$snippet_title,
          'greeting' => 'Hi, '.$user->name,
          'body' => 'Congratulations, You got your first '.$views. ' views on your new 
     snippet - '.$snippet_title,
          'body1' =>'',
          'thanks' => ' ',
          'actionText' => 'View snippet',
          'actionURL' => url(env('FRONTEND_URL').'/snippets/'.$slug)
                 ];
          Notification::send($user, new BBBnotifications($notificationdetails));

    }


via Chebli Mohamed

mercredi 12 octobre 2022

composer 1 out of memory - impossible to update to 2

Everytime I try to install a new package on my webserver, I run into composer error (after very long delay). What is the solution? What is the work around?

 pgodard@dedi13:~/public_html$ composer require setasign/fpdf:^1.8
 Warning from https://repo.packagist.org: Support for Composer 1 is deprecated and some packages will not be available. You should upgrade to Composer 2. See https://blog.packagist.com/deprecating-composer-1-support/
 Info from https://repo.packagist.org: #StandWithUkraine
 ./composer.json has been updated
 Loading composer repositories with package information
 Warning from https://repo.packagist.org: Support for Composer 1 is deprecated and some packages will not be available. You should upgrade to Composer 2. See https://blog.packagist.com/deprecating-composer-1-support/
 Info from https://repo.packagist.org: #StandWithUkraine
 Updating dependencies (including require-dev)
 
 Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 12288 bytes) in phar:///usr/bin/composer/src/Composer/DependencyResolver/RuleSetGenerator.php on line 64
 
 Check https://getcomposer.org/doc/articles/troubleshooting.md#memory-limit-errors for more infopgpgppgodard@dedi13:~/public_html$ 

If I try to update composer, I get another error...

pgodard@dedi13:~/public_html$ composer selfupdate --2
Updating to version 2.4.2 (2.x channel).
Downloading (100%)                                                
[Composer\Downloader\FilesystemException]                            
Filesystem exception:                                                
Composer update failed: "/usr/bin/composer" could not be written.    
rename(/usr/bin/composer): Failed to open stream: Permission denied  
 

On my local webserver on my mac, it works 100%.



via Chebli Mohamed

Laravel show pdf file in mobile device

I'm working on Laravel project where I have private url for pdf file like: http://10.10.1.10/dummy.pdf When I am using iframe to show pdf in mobile device, it is showing me download option instead showing pdf. I also checked online their peoples are suggesting google pdf viewer but due to private pdf url I cannot use the same. Please suggest a way that how can I achieve the same.



via Chebli Mohamed

mardi 11 octobre 2022

fill dynamic input with select html

I am trying to make a dynamic form which consists of being able to add rows dynamically and the same with a select I take the values ​​of the select and put them in the inputs of the first row, I would like to know how to fill in the other selects because it only works for me with the first row my select

enter image description here

function cambioOpciones(e) {
  const combo = document.getElementById('opciones'),
    [FECHA, MONEDA, NUMCTA, FAMILIA, CONCEPTO, FACTURA, DENOMINACION_SOCIAL, VENDEDOR] = document.getElementById('opciones').value.split('_');
  document.getElementById('fecha').value = FECHA;
  document.getElementById('moneda').value = MONEDA;
  document.getElementById('numcta').value = NUMCTA;
  document.getElementById('familia').value = FAMILIA;
  document.getElementById('Concepto').value = CONCEPTO;
  document.getElementById('showId').value = FACTURA;
  document.getElementById('denominacion').value = DENOMINACION_SOCIAL;
  document.getElementById('vendedor').value = VENDEDOR;
}

$(document).ready(function() {
  let row_number = 1;
  $("#add_row").click(function(e) {
    e.preventDefault();
    let new_row_number = row_number - 1;
    $('#venta' + row_number).html($('#venta' + new_row_number).html()).find('td:first-child');
    $('#ventas_table').append('<tr id="venta' + (row_number + 1) + '"></tr>');
    row_number++;
  });
  $("#delete_row").click(function(e) {
    e.preventDefault();
    if (row_number > 1) {
      $("#venta" + (row_number - 1)).html('');
      row_number--;
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<td>
  <select name="products[]" class="form-control" id="opciones" onchange='cambioOpciones();'>
    @foreach ($ventas1 as $ventas)
    <option value="_______">
      ---
    </option>
    @endforeach
  </select>
</td>


via Chebli Mohamed

Yajra datatable regenerate issue in Laravel 6

I am using laravel 6 and trying to regenerate yajra datatable by following

    var dataTable = $('#my_list').dataTable();
    dataTable.fnDestroy();
    getMyList();

It's working. But First of all it shows broken table(during data population) after that table become nicely visible. Here is my data-table configuration

DataTable({
       iDisplayLength: 15,
       processing: true,
       serverSide: true,
       lengthChange: false,
       searching: true,
       paging: true,
       ajax: 

How can I overcome this or introduce preloader during fetching data



via Chebli Mohamed

lundi 10 octobre 2022

How to Only Show Video in Instagram Embed Code?

I am using Laravel 5 and My client wants me to set and input in his admin page to add embedded Instagram videos code.

But does not want to show title, likes and other information.

Just plain video with autoplay.

I found out that you can just eliminate those pieces in the code Instagram gives you but my client just want to copy-paste.

Is there a way around this?



via Chebli Mohamed

jeudi 6 octobre 2022

Laravel mailer single authentication

I use Laravel 5.8.
In one of my scripts, a mail might be sent inside a very big loop. I use the following code :

Mail::send("myTemplate", $data, function (Message $m) use ($toAddress, $emailSubject) {
    $m->from(env("MAIL_USERNAME"), env("MAIL_FROM_NAME"));
    $m->to($toAddress, $toAddress)->subject($emailSubject);
});

My problem is that in some moment email server complains about too many authentications, and reject attempt to send mail.

Is there any way to avoid authentication on each delivery, and instead having one single authentication?



via Chebli Mohamed

Use values from an X table and replace them in a Y table that contains formulas, getting a Z table with these results - Laravel 8

I'm trying to get the values from a values table, replace them in the formulas table and consequently show these results in my view. My question is how can I get these values and replace them in the formula table in my Controller. I've done some research and read some things in the documentation, but with no success and no idea how I might be doing this.

For example:


Values Table = {"id": 1, "$ph_smp": 1.22, "$ph_kcl": 2.36}

Formula Table = {"id": 1, "$ph_smp": number_format((1.371+(0.868*$ph_kcl)), 2, \",\", \"\"), "$ph_kcl": number_format(($ph_kcl)), 2, \",\", \"\")}

And do as follows:


Formula Table = {"id": 1, "$ph_smp": 3,15, "$ph_kcl": 2,36}

I don't want to update the formulas table, but just have this result to be used in the view temporarily. Even because I will always need to use the formulas table to generate other results, depending on what is in the values table.

In other programming languages when you have, for example, y = x**2 + 2x and we need to print the result of y for a certain value is quite simple. But in Laravel I can't imagine how it would be done, because it's about values and formulas contained in tables.



via Chebli Mohamed

mercredi 5 octobre 2022

I'm working on frontend and Backend is in php laravel, the string are getting truncate, I don't know why? [closed]

 <div class="overview_content">
     <p class="view_paras">
              {!!ucfirst( str_replace('</p><p>','<br>',$course->overview))!!}
                    
        </p>
  </div>

Code look like this -

This is the structure been followed.

And the result is like in image - enter image description here

For more clear code - enter image description here



via Chebli Mohamed

How to run Laravel 8 on MAMP?

I have this in my composer.json

"require": {
    "php": "^8",
    "alkhachatryan/laravel-web-console": "^3.3",
    "barryvdh/laravel-dompdf": "^0.9.0",
    "doctrine/dbal": "^2.10",
    "fideloper/proxy": "^4.2",
    "fruitcake/laravel-cors": "^1.0",
    "guzzlehttp/guzzle": "^6.3",
    "intervention/image": "^2.3",
    "laravel/framework": "^8",
    "laravel/tinker": "^2.0",
    "laravelcollective/html": "~6.0",
    "league/flysystem-aws-s3-v3": "~1.0",
    "pusher/pusher-php-server": "^4.1"
},

I'm trying to run my Laravel app via MAMP v6.6

I kept getting

Fatal error: Composer detected issues in your platform: Your Composer dependencies require a PHP version ">= 8.1.0". You are running 8.0.8. in /Users/laravel-app/vendor/composer/platform_check.php on line 24

macOS 12.3

php --version

PHP 8.1.8 (cli) (built: Jul 8 2022 10:46:35) (NTS) Copyright (c) The PHP Group Zend Engine v4.1.8, Copyright (c) Zend Technologies with Zend OPcache v8.1.8, Copyright (c), by Zend Technologie



via Chebli Mohamed

I want to upload word document and view data in a text box using laravel

I created a form that user can enter the data in a text box and generate word document. Now I want to upload a word document and view the data in a text box. how can I do that using php in Laravel?



via Chebli Mohamed

mardi 4 octobre 2022

Wrong date and time showed

With this line:

<td><% district.created_at %></td>

I'm getting this output:

2022-08-06T09:14:58.000000Z

It should be like this:

2021-12-30 13:19:22

The correct printout is from Laravel 5.3 and the wrong from Laravel 9. What could be the problem and how to correct?



via Chebli Mohamed

lundi 3 octobre 2022

Disable dropdown in Laravel Blade

I have this dropdown i want to make it read only or disable

 

tried disabled also

 

but i want to disable options only the option that is pre-selected should be saved in database, using readonly i can change the dropdown and using disable i can't get its value.



via Chebli Mohamed

dimanche 2 octobre 2022

Laravel modular not routes with module

I am using "artem-schander/l5-modular": "^2.1" in laravel 6 . Package successfully installed. Also created a module name Employee. when I hit url like

<a href="" >Employee</a>

route (App/Modules/Employee/web.php)

Route::group(['module' => 'Employee', 'middleware' => ['auth'], 'namespace' => 'App\Modules\Employee\Http\Controllers'], function () {

     Route::get('employee-list', 'EmployeeController@welcome');
});

It shows 404 Not Found . How can I link it with module route ?



via Chebli Mohamed

samedi 1 octobre 2022

Searching with multiple tables in laravel

I have this search query

 $products = Product::query()
            ->where('name', 'LIKE', "%{$search}%")
            ->orWhere('slug', 'LIKE', "%{$search_any}%")
            ->where('status', 'Active')
            ->get();

i have user table which stores the user who listed the product and its relation is as follows

Product Model:

  public function user()
    {
        return $this->belongsTo(User::class);
    }

I have one field type in user table, i want if user enters search string matches type also then also all the products added by them should be returned i was trying this code but how can i combine both the queries

 $products = Product::query()
                ->where('name', 'LIKE', "%{$search}%")
                ->orWhere('slug', 'LIKE', "%{$search_any}%")
                ->where('status', 'Active')
                ->get();
 $productsAddedByUser = User::where('type', 'LIKE', "%{$search_any}%")->get();
// saved $productsAddedByUser result in this array $userIdarray
$productnew = Product::whereIn('user_id', $userIdarray)->get();

I want to combine both the results of $productnew and $products



via Chebli Mohamed