jeudi 26 août 2021

Query with empty results laravel eloquent

I´m traying to create statistics from my database. I´m changing application and before statistics was created from call table. But i change this and i was created a new table statistics and have this column:

id, id_ployed, call_id, created_at(nullable), updated_at(nullable)

and data example for example:

52,60,88988,4
53,60,88989,10
54,60,88990,6
62,9,88999,1

i have this function in my controller, but return empty data and it´s imposible:

$estadosLlamadas = EstadoLlamada::orderBy('desc')->get();

        if(isset($request->fromDate) && isset($request->toDate)){
            $fromDate = Carbon::parse($request->get('fromDate'));
            $toDate = Carbon::parse($request->get('toDate'));

            $fromDate = $fromDate->format('Y-m-d');
            $toDate = $toDate->format('Y-m-d');

        }else{
            $fromDate = new Carbon('first day of this month');
            $toDate = new Carbon('last day of this month');

            $fromDate = $fromDate->format('Y-m-d');
            $toDate = $toDate->format('Y-m-d');
        }

        $teleoperadoras = auth()->user()->whereIs('teleoperadora')->activos()->select(['id', 'nombre'])->orderBy('nombre', 'desc')->get();
        
        $array = [
            'toDate'   => $toDate,
            'fromDate' => $fromDate,
            'nombresEstados' => $estadosLlamadas->pluck('desc')->toArray(),
            'coloresEstados' => $estadosLlamadas->pluck('hex')->toArray()
        ];

        $query = Estadisticas::query()
            ->whereDate('estadisticas.created_at', '<=', $toDate)
            ->whereDate('estadisticas.created_at', '>=', $fromDate)
            ->whereIn('estadisticas.id_empleado', $teleoperadoras->pluck('id'))
            ->join('users', 'estadisticas.id_empleado', '=', 'users.id')->latest('estadisticas.updated_at')->get();


        foreach($teleoperadoras as $teleoperadora) {
            $array['teleoperadoras'][] = $teleoperadora->nombre;
            $array['id_teleoperadoras'][] = $teleoperadora->id;
            $array[$teleoperadora->id]['resultados'] = [];
            $array['llamadas'][] = $query->where('id_empleado', $teleoperadora->id)->count();

            $array['llamadasTodo'][$teleoperadora->id] = $query->where('id_empleado', $teleoperadora->id);

            foreach($estadosLlamadas as $estado) {
                $array[$teleoperadora->id]['resultados'][] = $query->where('id_empleado', $teleoperadora->id)
                                                            ->where('id_estado', $estado->id)->count();
            }
        }

        $array['nllamadas'] = $query->count();
        $array['fromDate'] = $fromDate . " 00:00:00";
        $array['toDate'] = $toDate . " 23:59:59";
        $roleUser = auth()->user()->getRoles()->first();

        return [
            'datos' => $array, 'estados' => $estadosLlamadas,
            'teleoperadoras' => $teleoperadoras, 'roleUser' => $roleUser,
        ];

this fill statics with chartJS:

$.ajax({
            type: 'GET',
            url: "",
            data: { 'fromDate': fromDate, 'toDate': toDate },
            success: function(response){
                console.log(response);

                $("#loadMe").modal('hide');

                var totalCall = 0;
                let totalCallByOperator = response["datos"]["llamadas"];

                $("#totalCall").append(response.datos.nllamadas)

                // append all teleoperator in view with calls number
                response["datos"]["teleoperadoras"].forEach(function(teleoperadora, index) {
                    $("#teleoperadoras").append('<b class="teleoperadora">'+teleoperadora + ": " + totalCallByOperator[index] +'</b> <br>');
                });

                // generate general statistics
                var ctx = document.getElementById('canvas1').getContext('2d');

                var myChart = new Chart(ctx, {
                    type: 'bar',
                
                    data: {
                        labels: response["datos"]["teleoperadoras"],
                        datasets: [{
                            label: 'Total de llamadas por operadora',
                            data: totalCallByOperator,
                            backgroundColor: [
                            'rgba(255, 99, 132, 0.2)',
                            'rgba(255, 159, 64, 0.2)',
                            'rgba(255, 205, 86, 0.2)',
                            'rgba(75, 192, 192, 0.2)',
                            'rgba(54, 162, 235, 0.2)',
                            'rgba(153, 102, 255, 0.2)',
                            'rgba(201, 203, 207, 0.2)'
                            ],
                            borderColor: [
                            'rgb(255, 99, 132)',
                            'rgb(255, 159, 64)',
                            'rgb(255, 205, 86)',
                            'rgb(75, 192, 192)',
                            'rgb(54, 162, 235)',
                            'rgb(153, 102, 255)',
                            'rgb(201, 203, 207)'
                            ],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            y: {
                                beginAtZero: true
                            }
                        }
                    }// end options

                }); // end chart object
            },
            error: function(xhr){
                alert(xhr.responseText);
            }
        });

and response from my controller its:

{datos: {9: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]},…}, estados: [,…],…}
datos: {9: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]},…}
9: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
11: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
22: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
23: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
24: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
25: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
26: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
49: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
50: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
60: {resultados: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]}
coloresEstados: ["#d26a5c", "#f3b760", "#46c37b", "#343a40", "#6c757d", "#d26a5c", "#d26a5c", "#5c80d1", "#70b9eb",…]
fromDate: "2021-08-01 00:00:00"
id_teleoperadoras: [9, 23, 24, 60, 22, 49, 11, 50, 25, 26]
llamadas: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
llamadasTodo: {9: [], 11: [], 22: [], 23: [], 24: [], 25: [], 26: [], 49: [], 50: [], 60: []}
nllamadas: 682
nombresEstados: ["ANULADA", "AUSENTE", "CONFIRMADA", "CONFIRMADA/ANULADA", "CONFIRMADA/AUSENTE", "ERRONEO NO EXISTE",…]
teleoperadoras: ["ARANZAZU SOLIS SANCHEZ", "CRISTINA LOPEZ UBRIC", "CRISTINA MORALES FERNANDEZ",…]
toDate: "2021-08-31 23:59:59"
estados: [,…]
roleUser: "admin"
teleoperadoras: [{id: 9, nombre: "ARANZAZU SOLIS SANCHEZ"}, {id: 23, nombre: "CRISTINA LOPEZ UBRIC"},…]

array "resultados" it´s where should be data to my statistics. This function it was ok before, but now not work.

My model its:

class Estadisticas extends Model
{
    protected $table = 'estadisticas';

    protected $primarykey = 'id';

    public $timestamps = false;

    protected $fillable = [
        'id_empleado', 'id_llamada', 'id_estado', 'created_at', 'updated_at'
    ];


    public function teleoperadora()
    {
        return $this->hasOne('App\User', 'id', 'id_empleado')->withDefault();
    }

    public function estado()
    {
        return $this->hasOne('App\EstadoLlamada', 'id', 'id_estado');
    }   
}

i hope that anybody can help me. thanks for read and sorry for my english



via Chebli Mohamed

Collapse sidebar when in certain pages (PHP) [duplicate]

Hope you are all doing well.

I'm working on a Codeigniter project for example I want when the user enters this page :

http://localhost:8080/admin/clients

I want the sidebar to stay shown but once he enters a sub-page like

http://localhost:8080/admin/clients/add 

I want the sidebar to be Hidden

Here's my code :

if($actual_link == admin_url().'/clients/**'){ ?>
    <body class="hide-sidebar">
<?php } else { ?>
    <body>
<?php } ?>

I tried this Code but it didn't work .



via Chebli Mohamed

laravel can't start first project [closed]

After downloading the latest php and installing composer. then installed laravel using the command composer global require laravel/installer

    Changed current directory to C:/Users/User/AppData/Roaming/Composer
Using version ^4.2 for laravel/installer
./composer.json has been created
Running composer update laravel/installer
Loading composer repositories with package information
Updating dependencies
Lock file operations: 13 installs, 0 updates, 0 removals
  - Locking laravel/installer (v4.2.8)
  - Locking psr/container (1.1.1)
  - Locking symfony/console (v5.3.6)
  - Locking symfony/deprecation-contracts (v2.4.0)
  - Locking symfony/polyfill-ctype (v1.23.0)
  - Locking symfony/polyfill-intl-grapheme (v1.23.1)
  - Locking symfony/polyfill-intl-normalizer (v1.23.0)
  - Locking symfony/polyfill-mbstring (v1.23.1)
  - Locking symfony/polyfill-php73 (v1.23.0)
  - Locking symfony/polyfill-php80 (v1.23.1)
  - Locking symfony/process (v5.3.4)
  - Locking symfony/service-contracts (v2.4.0)
  - Locking symfony/string (v5.3.3)
Writing lock file
Installing dependencies from lock file (including require-dev)
Package operations: 13 installs, 0 updates, 0 removals
    0 [>---------------------------]    0 [>---------------------------]
  - Installing symfony/polyfill-php80 (v1.23.1): Extracting archive
  - Installing symfony/process (v5.3.4): Extracting archive
  - Installing symfony/polyfill-mbstring (v1.23.1): Extracting archive
  - Installing symfony/polyfill-intl-normalizer (v1.23.0): Extracting archive
  - Installing symfony/polyfill-intl-grapheme (v1.23.1): Extracting archive
  - Installing symfony/polyfill-ctype (v1.23.0): Extracting archive
  - Installing symfony/string (v5.3.3): Extracting archive
  - Installing psr/container (1.1.1): Extracting archive
  - Installing symfony/service-contracts (v2.4.0): Extracting archive
  - Installing symfony/polyfill-php73 (v1.23.0): Extracting archive
  - Installing symfony/deprecation-contracts (v2.4.0): Extracting archive
  - Installing symfony/console (v5.3.6): Extracting archive
  - Installing laravel/installer (v4.2.8): Extracting archive
  0/13 [>---------------------------]   0%
 10/13 [=====================>------]  76%
 12/13 [=========================>--]  92%
 13/13 [============================] 100%
6 package suggestions were added by new dependencies, use `composer suggest` to see details.
Generating autoload files
11 packages you are using are looking for funding.
Use the `composer fund` command to find out more!`

After installation created a project laravel new example-app

 Creating a "laravel/laravel" project at "./example-app"
    Installing laravel/laravel (v8.6.1)
  - Installing laravel/laravel (v8.6.1): Extracting archive
    Created project in C:\test/example-app
> @php -r "file_exists('.env') || copy('.env.example', '.env');"
    Loading composer repositories with package information
    Updating dependencies
    Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - laravel/framework[v8.54.0, ..., 8.x-dev] require league/flysystem ^1.1 -> satisfiable by league/flysystem[1.1.0, ..., 1.x-dev].
    - league/flysystem[1.1.0, ..., 1.x-dev] require ext-fileinfo * -> it is missing from your system. Install or enable PHP's fileinfo extension.
    - Root composer.json requires laravel/framework ^8.54 -> satisfiable by laravel/framework[v8.54.0, v8.55.0, v8.56.0, 8.x-dev].

To enable extensions, verify that they are enabled in your .ini files:
    - C:\php7\php.ini
You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Then I performed cd example-app и php artisan serve. После выполнения php artisan serve gives an error message :

PHP Warning:  require(C:\test\example-app/vendor/autoload.php): Failed to open stream: No such file or directory in C:\test\example-app\artisan on line 18
PHP Fatal error:  Uncaught Error: Failed opening required 'C:\test\example-app/vendor/autoload.php' (include_path='.;C:\php\pear') in C:\test\example-app\artisan:18
Stack trace:
#0 {main}
  thrown in C:\test\example-app\artisan on line 18

After walking through the forums, I realized that there was not enough folder vendor in project Project with files

After adding the vendor folder to the project using the command composer dump-autoload.The folder was added but after running the command composer dump-autoload a new error popped up :

Generating optimized autoload files
Class Illuminate\Foundation\ComposerScripts is not autoloadable, can not call post-autoload-dump script
> @php artisan package:discover --ansi
PHP Fatal error:  Uncaught Error: Class "Illuminate\Foundation\Application" not found in C:\test\example-app\bootstrap\app.php:14
Stack trace:
#0 C:\test\example-app\artisan(20): require_once()
#1 {main}
  thrown in C:\test\example-app\bootstrap\app.php on line 14
Script @php artisan package:discover --ansi handling the post-autoload-dump event returned with error code 255

Then I tried to execute the command php artisan serve .Throws this error :

PHP Fatal error:  Uncaught Error: Class "Illuminate\Foundation\Application" not found in C:\test\example-app\bootstrap\app.php:14
Stack trace:
#0 C:\test\example-app\artisan(20): require_once()
#1 {main}
  thrown in C:\test\example-app\bootstrap\app.php on line 14

Then, walking around the forums, I just did not run to fix this problem I tried: Composer update, Composer install, composer update --no-scripts

composer dump-autoload
composer install --no-scripts

I also tried this :

php artisan clear-compiled
composer dump-autoload

And tried to delete the vendor folder.

And so I tried it, though it says that there is no such file:

composer update --no-scripts
cd bootstrap/cache/->rm -rf *.php
composer dump-autoload

Nothing helped . I do not know what to do. And how to solve this problem.



via Chebli Mohamed

mercredi 25 août 2021

problem with id does not show the correct and repeats

i have a problem with my online shift application

https://i.imgur.com/d1O5Eao.png

the user can view their shift requests. The problem is that clicking view (...) always redirects to shift ID 93 in the two registers

https://i.imgur.com/33hRcLa.png

Controller:

    public function inicio(){
    
        if (Auth::guest()) {
          return redirect()->route("login");
        }
    
        $config = Configuraciones::findOrFail(0);
       
       // Solicitudes = REQUEST 

        $solicitudes = Solicitudes::where('user_id', Auth::User()->id)->orderByDesc('created_at')->take(5)->get();

 GET THE ID OF THE REQUEST FROM THE LOGED USER
        $solicitud = Solicitudes::where('user_id', Auth::User()->id)->first();
    


// GET THE SHIFT 'id' RELATED TO THE 'id' OF THE request
        $eventos = Eventos::where('solicitud_id', $solicitud->id)->first();
       
       
        return view('solicitudes.inicio',compact('solicitudes','config','eventos'))->with($data);
       }

Blade: `

@foreach($solicitudes as $solicitud)
                                        @if(Auth::user()->id == $solicitud->user_id)
                                        <tr>
                                            <td></td>
                                            <td></td>
                                            <td class="text-center">
                                                @if($solicitud->estado == '0')
                                                <span class="badge badge-primary">Pendiente</span>
                                                @elseif($solicitud->estado == '1')
                                                <span class="badge badge-success">Aceptada</span>
                                                @elseif($solicitud->estado == '2')
                                                <span class="badge badge-danger">Rechazada</span>
                                                @endif
                                            </td>
                                            <td class="text-center">
                                                
                                                <div class="dropdown custom-dropdown">
                                                    <a class="dropdown-toggle" href="#" role="button" id="dropdownMenuLink1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                                                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-more-horizontal"><circle cx="12" cy="12" r="1"></circle><circle cx="19" cy="12" r="1"></circle><circle cx="5" cy="12" r="1"></circle></svg>
                                                    </a>

                                                    <div class="dropdown-menu" aria-labelledby="dropdownMenuLink1">
                                                        <a class="dropdown-item" href="/turno/">Ver</a>
                                                      
                                                    </div>
                                                </div>

                                            </td>
                                        </tr>
                                        @endif
                                        @endforeach`

Try using: $eventos = Eventos::where('solicitud_id', $solicitud->id)->get();

but it give error: Property [id] does not exist on this collection instance.

What can i do to get the correct shift ID? and that the same thing is not always repeated



via Chebli Mohamed

Laravel Save A Generated Pdf Inside A Queue

I have a blade where i converts Html to a pdf and save it on my local , then i am using a live url to get a pdf and save it on my local Then I am using a laravel library to merge both pdf's and it will generate a single pdf by embeding, It was working fine earlier, now I have a high-quality pdf where it takes much time to merge, due to it, it is takeing mome time and it returns a max limit memory issue,

so i tried to do it on Queue

this is my code

 $ecg_link = 'https://storage.googleapis.com/staging.uk-production.appspot.com/test1111.pdf';
    
 $ecg_pdf = isset($ecg_link) ?  $ecg_link : '';

 if($ecg_pdf){
        $ecg_contents = file_get_contents($ecg_link);
    
        if (!File::exists(storage_path('app/public/screening/pdf'))){
            File::makeDirectory(storage_path('app/public/screening/pdf'), 0777, true, true);
        }

        \Storage::disk('public')->put('screening/pdf/'.$screening_id.'.pdf', $ecg_contents);
      
        $pdf = PDF::loadView('participants.test', 
         compact('participantdata','Allopurinol','stn_assetreview'));

        if (!File::exists(storage_path('app/public/screening/pdf/temporary-pdf'))){
            File::makeDirectory(storage_path('app/public/screening/pdf/temporary-pdf'), 0777, 
        true, true);
        }
        $pdf->save(storage_path('app/public/screening/pdf/temporary-pdf/'.$screening_id.'.pdf'));

        $pdfMerger = PDFMerger::init(); //Initialize the merger
        $pdfMerger->addPDF(storage_path('app/public/screening/pdf/temporary-pdf/'.$screening_id.'.pdf'), 'all');
        $pdfMerger->addPDF(storage_path('app/public/screening/pdf/'.$screening_id.'.pdf'), 'all' );
       

        $pdfMerger->merge();

        if (!File::exists(storage_path('app/public/screening/pdf/final-pdf'))){
            File::makeDirectory(storage_path('app/public/screening/pdf/final-pdf'), 0777, true, true);
        }
        $pdfMerger->save($screening_id.'.pdf', "download");

when i use queue , i am unable to download the excel since its in queue , I sthere any way i can download the excel , else can i send this pdf over a mail ???

thank you



via Chebli Mohamed

how to get users group by roles in laravel query builder

I have three tables 1 users table, 2 roles table and 3 role_users table as pivot table. Each user may have multiple roles such as editor and publisher at the same time maybe

Tables Structure

  1. Users                  id name email
  2. Roles                  id name
  3. Role_users          id role_id user_id

first user has 2 different roles editor & publisher with my query it's repeating the user with new role every time. How can I group them as array of roles in result

Query

        $query = DB::table('users')
       ->select(
        'users.name As name',
        'users.email As email',
        'users.status As status',
        'roles.name As role'
        );

    $query->leftjoin('role_users', 'users.id', '=', 'role_users.user_id');
    $query->leftjoin('roles', 'role_users.role_id', '=', 'roles.id');
    $query->groupBy('roles.name');
    $result = $query->get();

    dd($result->toArray());

Result Required

    "name": "Billyshawn"
    "email": "billy@shawn.com"
    "role": ["editor","publisher"]


via Chebli Mohamed

Cache Management Ubuntu 18.04 LTS

I have a Laravel 5.6 (including NodeJS) application hosted on AWS cloud (Ubuntu 18 LTS) with available RAM of upto 4GB.

But I am observing the available amount of RAM decreasing due to some unknown reasons to me.

I saw the output of free -m command via terminal and the results show more than 1GB of cached data.

Could you guys illuminate me more into that as to why cache is increasing.

Can I browse to that folder if cache is being stored temporarily.

Thank You in anticipation.



via Chebli Mohamed