noblemfd

noblemfd

Member Since 5 Months Ago

Experience Points
15,570
Total
Experience

4,430 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
0
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 4
15,570 XP
May
27
3 days ago
Activity icon

Started a new Conversation How To Refresh External Api Into Db Using Guzzle

I am having thismodel in my Laravel-5.8 project: Employee

Employee

class Employee extends Model { protected $table = 'employees';

   protected $primaryKey = 'id';

   protected $fillable = [
              'staff_code',
              'first_name',
              'last_name',
              'department_id',
          ];

  public function department()
  {
     return $this->belongsTo('App\Department','department_id');
  }    

}

That is,:

App\Employee

Also I have an external api that comes in form of JSON get request.

https://api.employees.net/allemployees

I have viewed it with postman get request and I have something like this:

 {
    "ID": "1",
    "StaffCode": "STC001",
    "FirstName": "Japheth",
    "LastName": "Shalom",
    "DepartmentCode": "dep2",
 },
 {
    "ID": "2",
    "StaffCode": "STC002",
   "FirstName": "Ahitophel",
   "last_name": "Nedum",
   "DepartmentCode": "dep1",
},
{
    "ID": "3",
    "StaffCode": "STC003",
    "FirstName": "Joash",
    "FirstName": "Nathan",
    "DepartmentCode": "dep2",
 },

and so on... this continues

Already I have created this function:

 use App\Employee;
 use App\Department;

 public function index() 
 {  
    $client = new GuzzleHttp\Client();
    $res = $client->request('GET','https://api.employees.net/allemployees');
    $clientdatas = json_decode($res, true);

   ...
 }

Apart from the id and staff_code that are UNIQUE, any of the others fields too can change.

Since any of the fields can change at any time. How do I refresh the entire db, save new data and update changes?

Thank you

Activity icon

Awarded Best Reply on Nginx: [emerg] BIO_new_file("/etc/letsencrypt/live/test.site2.net/fullchain.pem") Failed (SSL: Error

@bobbybouwmann - I deleted the initial default file and it eventually works.

Thanks

May
26
4 days ago
Activity icon

Replied to How To Have Phpmyadmin On Nginx VirtualHost Ubuntu

@drewdan

How do I do this with what I already have running?

Why not instead try using mysql community workbench and connect to your server with an SSH connection instead, it will be vastly more secure and one less thing to configure on your server

Kindly advice.

Thanks

Activity icon

Started a new Conversation How To Have Phpmyadmin On Nginx VirtualHost Ubuntu

I have my Laravel-5.8 projects deployed to DigitalOcean using nginx VirtualHost Ubuntu.

The IP is someting like 22.11.44.13

site1 path:  /var/www/html/site1

site2 path:  /var/www/html/site2test

[email protected]

sites-available

/etc/nginx/sites-available/site1.conf

/etc/nginx/sites-available/site2.conf

IP Address:

22.11.44.13

Domain Names:

site1.net

site2.net

I have database for each site

site1db

site2db

I am using php-7.3

Now how do I create phpmyadmin using nginx?

Thank you.

Activity icon

Replied to Nginx: [emerg] BIO_new_file("/etc/letsencrypt/live/test.site2.net/fullchain.pem") Failed (SSL: Error

@bobbybouwmann - I deleted the initial default file and it eventually works.

Thanks

May
25
5 days ago
Activity icon

Replied to Website Currently Unable To Handle This Request. HTTP ERROR 500 On Ubuntu

@michaloravec - This is what I got in the Log:

2020/05/25 21:24:08 [error] 27503#27503: *230 FastCGI sent in stderr: "PHP message: PHP Fatal error:  
Uncaught ErrorException: file_put_contents(/var/www/html/laravelsite/storage/framework/views/9b2eee1fb2a24f5c67cfcf6e088831dfc464bc5f.php): failed to open stream: Permission denied in /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:122
Stack trace:
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'file_put_conten...', '/var/www/html/p...', 122, Array)
#1 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php(122): file_put_contents('/var/www/html/p...', '<!doctype html>...', 0)
#2 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php(140): Illuminate\Filesystem\Filesystem->put('/var/www/html/p...', '<!doctype html>...')
#3 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(51): Illuminate\View\Compilers\BladeCompiler->compile('/...PHP message: PHP Fatal error:  Uncaught 
ErrorException: file_put_contents(/var/www/html/laravelsite/storage/framework/views/9b2eee1fb2a24f5c67cfcf6e088831dfc464bc5f.php): failed to open stream: Permission denied in /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:122
Stack trace:
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'file_put_conten...', '/var/www/html/p...', 122, Array)
#1 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php(122): file_put_contents('/var/www/html/p...', '<!doctype html>...', 0)
#2 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php(140): Illuminate\Filesystem\Filesystem->put('/var/www/html/p...', '<!doctype html>...')
#3 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(51): 
2020/05/25 21:24:10 [error] 27503#27503: *230 FastCGI sent in stderr: "PHP message: PHP Fatal error:  
Uncaught ErrorException: file_put_contents(/var/www/html/laravelsite/storage/framework/views/9b2eee1fb2a24f5c67cfcf6e088831dfc464bc5f.php): failed to open stream: Permission denied in /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:122
Stack trace:
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'file_put_conten...', '/var/www/html/p...', 122, Array)
#1 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php(122): file_put_contents('/var/www/html/p...', '<!doctype html>...', 0)
#2 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php(140): Illuminate\Filesystem\Filesystem->put('/var/www/html/p...', '<!doctype html>...')
#3 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(51): Illuminate\View\Compilers\BladeCompiler->compile('/...PHP message: PHP Fatal error:  Uncaught 
ErrorException: file_put_contents(/var/www/html/laravelsite/storage/framework/views/9b2eee1fb2a24f5c67cfcf6e088831dfc464bc5f.php): failed to open stream: Permission denied in /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php:122
Stack trace:
#0 [internal function]: Illuminate\Foundation\Bootstrap\HandleExceptions->handleError(2, 'file_put_conten...', '/var/www/html/p...', 122, Array)
#1 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/Filesystem/Filesystem.php(122): file_put_contents('/var/www/html/p...', '<!doctype html>...', 0)
#2 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/View/Compilers/BladeCompiler.php(140): Illuminate\Filesystem\Filesystem->put('/var/www/html/p...', '<!doctype html>...')
#3 /var/www/html/laravelsite/vendor/laravel/framework/src/Illuminate/View/Engines/CompilerEngine.php(51):
Activity icon

Started a new Conversation Website Currently Unable To Handle This Request. HTTP ERROR 500 On Ubuntu

I deployed my Laravel-5.8 project to DigitalOcean Ubuntu. Initially, it was working, but suddenly when I type the url on the browser I got this error:

This page isn’t working tlaravelsite.net is currently unable to handle this request. HTTP ERROR 500

How do I resolve this?

Thanks

Activity icon

Replied to Nginx: [emerg] BIO_new_file("/etc/letsencrypt/live/test.site2.net/fullchain.pem") Failed (SSL: Error

@bobbybouwmann

/etc/nginx/sites-available	

site1.net,conf

server {
listen 80;
listen [::]:80;

server_name site1.net;
return 301 https://$server_name$request_uri;
}

server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name site1.net;
root /var/www/html/site1;

ssl_certificate /etc/letsencrypt/live/site1.net/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/site1.net/privkey.pem;

ssl_protocols TLSv1.2;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
ssl_prefer_server_ciphers on;

add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";

index index.php index.html index.htm;

charset utf-8;

location / {
        try_files $uri $uri/ /index.php?$query_string;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
}



 location ~ /\.ht {
        deny all;
 }

 location ~ /.well-known {
        allow all;
 }
}

site2.net,conf

server {
listen 80;
listen [::]:80;

server_name site2.net;
return 301 https://$server_name$request_uri;
}

server {
listen 443 ssl http2;
listen [::]:443 ssl http2;
server_name site1.net;
root /var/www/html/site1test;

ssl_certificate /etc/letsencrypt/live/site2.net/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/site2.net/privkey.pem;

ssl_protocols TLSv1.2;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
ssl_prefer_server_ciphers on;

add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";

index index.php index.html index.htm;

charset utf-8;

location / {
        try_files $uri $uri/ /index.php?$query_string;
}

location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
}



 location ~ /\.ht {
        deny all;
 }

 location ~ /.well-known {
        allow all;
 }
}

same for sites-enabled.

Activity icon

Replied to Nginx: [emerg] BIO_new_file("/etc/letsencrypt/live/test.site2.net/fullchain.pem") Failed (SSL: Error

@bobbybouwmann - Yes.

Also I copied:

ssl_protocols TLSv1.2;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA512:DHE-RSA-AES256-GCM-SHA512:ECDHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384;
ssl_prefer_server_ciphers on;

as it is in site1.conf into site2.conf

Activity icon

Started a new Conversation How To Copy The Content Of My Project Folder To Another Folder In Ubuntu

I have my Laravel-5.8 project in this folder in this folder:

/var/www/html/site1

How to I copy the replicate the content of site1 into

/var/www/html/site2

using command in Ubuntu?

Thank you.

Activity icon

Started a new Conversation Nginx: [emerg] BIO_new_file("/etc/letsencrypt/live/test.site2.net/fullchain.pem") Failed (SSL: Error

I have uploaded my Laravel-5.8 to the DigitalOcean Ubuntu server.

The IP is someting like 22.11.44.13 and the domain is site1.net

site1 path:  /var/www/html/site1

site2 path:/var/www/html/site2test

I decided to create virtual hosts to be able to host multiple applications on the same server.

So, I did:

[email protected]: cp /etc/nginx/sites-available/default /etc/nginx/sites-available/site1.conf
[email protected]: cp /etc/nginx/sites-available/default /etc/nginx/sites-available/site2.conf

Then

[email protected]: ln -s /etc/nginx/sites-available/site1.conf	/etc/nginx/sites-enabled/
[email protected]: ln -s /etc/nginx/sites-available/site2.conf	/etc/nginx/sites-enabled/

Having set up everything. site1 is running https /SSH

So I want to do the same for site2. I registered the domain name with the same IP as site 1 in order to do VirtualHost. So, when I ran

  [email protected]: nginx -t

I got this:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful

I copied

ssl_ciphers from site2 to site2

For site2 https/SSH I did:

sudo certbot certonly --webroot --webroot-path=/var/www/html/site2test -d test.site2.net -d www.test.psite2.net

Now when I tried to launch site2 as https://test.site2.net/

I got this error:

403 Forbidden
nginx/1.14.0 (Ubuntu)

How do I resolve this? Thanks

May
24
6 days ago
Activity icon

Started a new Conversation Nginx: Configuration File /etc/nginx/nginx.conf Test Failed

I uploaded Laravel-5.8 projects to the DigitalOcean Server using Ubuntu. The site is running very well. Later I decided to create virtual hosts to be able to host multiple applications on the same server.

I followed this link:

https://graspingtech.com/nginx-virtual-hosts-ubuntu-16-04/

Now I did:

[email protected]: cp /etc/nginx/sites-available/default /etc/nginx/sites-available/site1.conf
[email protected]: cp /etc/nginx/sites-available/default /etc/nginx/sites-available/site2.conf

Then

[email protected]: ln -s /etc/nginx/sites-available/site1.conf	/etc/nginx/sites-enabled/
[email protected]: ln -s /etc/nginx/sites-available/site2.conf	/etc/nginx/sites-enabled/

Then when I did:

[email protected]: nginx -t

I got this error:

nginx: configuration file /etc/nginx/nginx.conf test failed

This is the content of /etc/nginx/nginx.conf

ser www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
worker_connections 768;
# multi_accept on;
}

http {

##
# Basic Settings
##

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
# server_tokens off;

# server_names_hash_bucket_size 64;
# server_name_in_redirect off;

include /etc/nginx/mime.types;
default_type application/octet-stream;

##
# SSL Settings
##

ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;

##
# Logging Settings
##

access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;

##
# Gzip Settings
##

gzip on;

# set client body size to 5M #
client_max_body_size 24000M;

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}

How do I resolve this?

Thank you

May
23
1 week ago
Activity icon

Replied to How To Configure Multiple Laravel Projects On DigitalOcean Ubuntu

@tray2 - How about if I want to make the new one a subdomain of the already existing one?

May
22
1 week ago
Activity icon

Awarded Best Reply on Laravel - My NGINX Suddenly Becomes Inactive In Ubuntu

Problem solved Thanks.

This is what I did:

ps -ef |grep nginx

netstat -tulpn |grep 80

service nginx start
Activity icon

Replied to Laravel - My NGINX Suddenly Becomes Inactive In Ubuntu

Problem solved Thanks.

This is what I did:

ps -ef |grep nginx

netstat -tulpn |grep 80

service nginx start
Activity icon

Replied to Laravel - My NGINX Suddenly Becomes Inactive In Ubuntu

@bobbybouwmann The error.log is empty. But when I typed my site url I got this:

This site can’t be reached mysite.net refused to connect. Try:

Checking the connection Checking the proxy and the firewall ERR_CONNECTION_REFUSED

When I did this: sudo service nginx restart

I got:

Job for nginx.service failed because the control process exited with error code.
See "systemctl status nginx.service" and "journalctl -xe" for details.

sudo systemctl status nginx

gives:

 nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Fri 2020-05-22 22:17:30 UTC; 2min 49s ago
  Docs: man:nginx(8)
  Process: 13408 ExecStop=/sbin/start-stop-daemon --quiet --stop --retry QUIT/5 --pidfile /run/nginx
  Process: 16144 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, s
 Main PID: 2865 (code=exited, status=0/SUCCESS)

May 22 22:17:30 MySite systemd[1]: Starting A high performance web server and a reverse proxy se
May 22 22:17:30 MySite nginx[16144]: nginx: [emerg] BIO_new_file("/etc/letsencrypt/live/test.peo
May 22 22:17:30 MySite nginx[16144]: nginx: configuration file /etc/nginx/nginx.conf test failed
May 22 22:17:30 MySite systemd[1]: nginx.service: Control process exited, code=exited status=1
May 22 22:17:30 MySite systemd[1]: nginx.service: Failed with result 'exit-code'.
May 22 22:17:30 MySite systemd[1]: Failed to start A high performance web server and a reverse p

What do I do?

Please

Activity icon

Replied to Laravel - My NGINX Suddenly Becomes Inactive In Ubuntu

@bobbybouwmann - Where do I get that? I check /etc/nginx

I ran nginx -t and I got:

nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
Activity icon

Replied to Laravel - My NGINX Suddenly Becomes Inactive In Ubuntu

Where do I get that? I check /etc/nginx

Activity icon

Started a new Conversation Laravel - My NGINX Suddenly Becomes Inactive In Ubuntu

I deployed a Laravel (PHP) application on DigitalOcean Ubuntu-18 using NGINX. Everything was working perfectly, until suddenly the server application stopped.

I observed that NGINX is inactive and I tried to restart, but failed.

How do I resolve this?

Thank yo

Activity icon

Started a new Conversation How To Configure Multiple Laravel Projects On DigitalOcean Ubuntu

Currently I have a single Laravel Application running on DigitalOcean/Ubuntu-18. I use Bitwise-SSH Client to access it and perform other configurations. It is running live. Its IP address is like 22.11.44.13

  1. Now I want to deploy other Applications on the same platform without tampering with the Initial one. One for testing, the other for Development purpose and the Last is a real Application.

  2. The other concern I have is the configuration. I used NGINX for the current one.

  3. And what do you think to host different projects on the same droplet (Laravel projects) ?

How do I achieve this?

Activity icon

Started a new Conversation How To Display Both Count And Percentage (%) In Chart Js Pie Chart

In my Laravel-5.8, I have used chartjs to display total male and female counts (total number of male and female)

as shown below:

Controller:

public function report()
{
    $userCompany = Auth::user()->company_id;
    $userId = Auth::user()->id;

$gender_record = HrEmployee::selectRaw('count(gender_id) as count,gender_id, if (gender_id = 1, "Male", "Female") as gender')->where('company_id', $userCompany)->groupBy('gender_id')->get();        
$gender_data = [];

foreach($gender_record as $row) {
   $gender_data['gender_label'][] = $row->gender;
   $gender_data['gender_data'][] = (int) $row->count;
 }

 $gender_data['gender_chart_data'] = json_encode($gender_data);    
    
    return view('report-default', $gender_data);       
}

view

          <div class="card-body">
            <canvas id="empGender" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>
          </div>

    <script src="{{ asset('theme/adminlte3/plugins/chart.js/Chart.min.js') }}"></script>

   <script>
     $(function () {
      /* ChartJS
       * -------
       * Charts using ChartJS
       */

   //-------------
   //- GENDER-EMPLOYEE CHART -
   //-------------
   // Get context with jQuery - using jQuery's .get() method.
  var genderData = JSON.parse(`<?php echo $gender_chart_data; ?>`);
  var genderChartCanvas = $('#empGender').get(0).getContext('2d')
  var genderData        = {

  labels: genderData.gender_label,
    datasets: [
    {
    data: genderData.gender_data,
      backgroundColor : [
            '#f56954', 
            '#00a65a', 
            '#f39c12', 
            '#00c0ef',               
      ],
            borderColor: [
            'rgba(255, 99, 132, 1)',
            'rgba(54, 162, 235, 1)',
        ],
        borderWidth: 1          
     }  
  ]
 }
 var genderOptions     = {
    maintainAspectRatio : true,
    responsive : true,
    cutoutPercentage: 80,

 }
 //Create pie or douhnut chart
  var genderChart = new Chart(genderChartCanvas, {
   type: 'doughnut',
   data: genderData,
   options: genderOptions      
   })

   })   
   </script>

Diagram:

https://i.stack.imgur.com/JxEuw.png

What I have as shown above only displays Total counts per Gender as shown above.

How do I make it also to include the percentage per Gender?

Thank you.

May
21
1 week ago
Activity icon

Started a new Conversation Production.ERROR: SQLSTATE[42000]: Syntax Error Or Access Violation: 1055 Expression #1 Of ORDER BY Clause Is Not In GROUP BY In Ubuntu

This code was working perfectly on my local system,:

     $all_leave_record = HrLeaveRequest::select(DB::raw("COUNT(leave_status) as count"), DB::raw("MONTHNAME(created_at) as month"))
        ->where('company_id', $userCompany)
        ->whereYear('created_at', date('Y'))
        ->orderBy(DB::raw("MONTH(created_at)"), 'ASC')
       ->groupBy(DB::raw("MONTHNAME(created_at)"))
        ->get();
    $all_leave_data = [];

    foreach($all_leave_record  as $row) {
       $all_leave_data['leave_label'][] = $row->month;
       $all_leave_data['all_leave_data'][] = (int) $row->count;
     }
     $all_leave_data['all_leave_chart_data'] = json_encode($all_leave_data); 

        $approved_leave_record = HrLeaveRequest:: select(DB::raw("COUNT(leave_status) as count"), DB::raw("MONTHNAME(created_at) as month"))
             ->where('company_id', $userCompany)
        ->where('leave_status', '=', 4)
        ->whereYear('created_at', date('Y'))
        ->orderBy(DB::raw("MONTH(created_at)"), 'ASC')
       ->groupBy(DB::raw("MONTHNAME(created_at)"))
        ->get();
    //    dd($approved_leave_record);
    $approved_leave_data = [];

    foreach($approved_leave_record  as $row) {
       $approved_leave_data['leave_label'][] = $row->month;
       $approved_leave_data['approved_leave_data'][] = (int) $row->count;
     }
   $approved_leave_data['approved_leave_chart_data'] = json_encode($approved_leave_data); 
   
     //Rejected Leaves          
    $rejected_leave_record = HrLeaveRequest::select(DB::raw("COUNT(leave_status) as count"), DB::raw("MONTHNAME(created_at) as month"))
        ->where('company_id', $userCompany)
        ->where('leave_status', '=', 3)
        ->whereYear('created_at', date('Y'))
        ->orderBy(DB::raw("MONTH(created_at)"), 'ASC')
       ->groupBy(DB::raw("MONTHNAME(created_at)"))
        ->get();
    
    $rejected_leave_data = [];

    foreach($rejected_leave_record  as $row) {
       $rejected_leave_data['leave_label'][] = $row->month;
       $rejected_leave_data['rejected_leave_data'][] = (int) $row->count;
     }
   $rejected_leave_data['rejected_leave_chart_data'] = json_encode($rejected_leave_data); 

but when I deployed to Ubuntu 18 server, I got this error:

production.ERROR: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'hr_leave_requests.created_at' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select COUNT(leave_status) as count, MONTHNAME(created_at) as month from hr_leave_requests where company_id = 1 and year(created_at) = 2020 group by MONTHNAME(created_at) order by MONTH(created_at) asc) {"userId":2,"exception":"[object] (Illuminate\Database\QueryException(code: 42000): SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'hr_leave_requests.created_at' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by (SQL: select COUNT(leave_status) as count, MONTHNAME(created_at) as month from hr_leave_requests where company_id = 1 and year(created_at) = 2020 group by MONTHNAME(created_at) order by MONTH(created_at) asc) at /var/www/html/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, Doctrine\DBAL\Driver\PDOException(code: 42000): SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'hr_leave_requests.created_at' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by at /var/www/html/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:63, PDOException(code: 42000): SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'hr_leave_requests.created_at' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by at /var/www/html/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOConnection.php:61)

How do I get it resolved.

Thank you

Activity icon

Started a new Conversation How To Represent Month Numeric With Alphabets

I have this query:

    $employee_record = Employee::select(DB::raw("COUNT(employee_status) as count"), DB::raw("MONTH(created_at) as month"))
        ->where('company_id', $userCompany)
        ->whereYear('created_at', date('Y'))
        ->orderBy(DB::raw("MONTH(created_at)"), 'ASC')
       ->groupBy(DB::raw("MONTH(created_at)"))
        ->get();

How do I modify the query and in :

DB::raw("MONTH(created_at) as month"))

represent 1 = January, 2=February, 3=March ... etc

Thanks

Activity icon

Started a new Conversation Leave Status Is Giving Wrong Result In Chartjs

In my Laravel-5.8 Application I am displaying Employee Leave Status on BarChart using ChartJs

Controller

public function leave()
{
    $userCompany = Auth::user()->company_id;
    $userId = Auth::user()->id;
    $userEmployee = Auth::user()->employee_id;
    
     // All Leave Requests
    $allEmployeeLeaves = HrLeaveRequest::select(DB::raw("COUNT(leave_status) as count"))
        ->where('company_id', $userCompany)
        ->whereYear('created_at', date('Y'))
        ->orderBy(DB::raw("MONTH(created_at)"), 'ASC')
        ->groupBy(DB::raw("MONTH(created_at)"))
        ->get()->toArray();
    $allEmployeeLeaves = array_column($allEmployeeLeaves, 'count');     
    
//Approved Leaves
    $approvedLeaves = HrLeaveRequest::select(DB::raw("COUNT(leave_status) as count"))
        ->where('company_id', $userCompany)
        ->where('leave_status', '=', 4)
        ->whereYear('created_at', date('Y'))
        ->orderBy(DB::raw("MONTH(created_at)"), 'ASC')
        ->groupBy(DB::raw("MONTH(created_at)"))
        ->get()->toArray();
    $approvedLeaves = array_column($approvedLeaves, 'count'); 
    
// Rejected Leaves
    $rejectedLeaves = HrLeaveRequest::select(DB::raw("COUNT(leave_status) as count"))
        ->where('company_id', $userCompany)
        ->where('leave_status', 3)
        ->whereYear('created_at', date('Y'))
        ->orderBy(DB::raw("MONTH(created_at)"), 'ASC')
        ->groupBy(DB::raw("MONTH(created_at)"))
        ->get()->toArray();
    $rejectedLeaves = array_column($rejectedLeaves, 'count');          
 
    
    return view('leave-default')
            ->with('allEmployeeLeaves',json_encode($allEmployeeLeaves,JSON_NUMERIC_CHECK))
            ->with('approvedLeaves',json_encode($approvedLeaves,JSON_NUMERIC_CHECK))
            ->with('rejectedLeaves',json_encode($rejectedLeaves,JSON_NUMERIC_CHECK));       
}   

From the Query Above I want to display a Bar Chart for:

  1. All Leave Requests

  2. Approved Leave

  3. Rejected Leave

Actually when leave_status = 3, it is rejected leaves and leave_status = 4 is approved leave.

View

          <div class="card-body">
            <div class="chart">
              <canvas id="leaveBarChart" style="min-height: 250px; height: 450px; max-height: 250px; max-width: 100%;"></canvas>
            </div>
          </div>

<script src="{{ asset('theme/adminlte3/plugins/chart.js/Chart.min.js') }}"></script>

<script>
    var month = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var data_all_leaves = <?php echo $allEmployeeLeaves; ?>;
    var data_approved_leaves = <?php echo $approvedLeaves; ?>;
    var data_rejected_leaves = <?php echo $rejectedLeaves; ?>;


    var barChartData = {
        labels: month,
        datasets: [{
            label: 'All Leave Requests',
            backgroundColor: "#f56954",
            data: data_all_leaves
        }, {
            label: 'Approved Leaves',
            backgroundColor: "#00a65a",
            data: data_approved_leaves
        }, {
            label: 'Rejected Leaves',
            backgroundColor: "#f39c12",
            data: data_rejected_leaves
        }]
    };


    window.onload = function() {
        var ctx = document.getElementById("leaveBarChart").getContext("2d");
        window.myBar = new Chart(ctx, {
            type: 'bar',
            data: barChartData,
            options: {
                elements: {
                    rectangle: {
                        borderWidth: 2,
                        borderColor: 'rgba(255, 99, 132, 1)',
                        borderSkipped: 'bottom'
                    }
                },
                responsive: true,
                maintainAspectRatio     : true,
                title: {
                    display: true,
                    text: 'Monthly Leave Status'
                }
            }
        });


    };
  </script>

This is the displayed resuled

https://i.stack.imgur.com/l6yjN.png

I expected the Barchart to display:

All Leaves, Rejected Leaves and Approved Leave. However, I have these three (3) observations.

  1. The chart only display All Leave, which is 2. This comprise of Approved Leave (1) and Rejected Leave (1). It didn't display Approved and Rejected Leaves.

  2. All the Leave are in May, but it put them in January

  3. The Leave counts on the BarChart are in decimal places (1.00, 1.10 ...) instaed of 1, 2 ...

How do I corrected all these?

Thank you

Activity icon

Replied to How To Count All The Gender Fields For Charts

I want to draw bar chart using chartjs. That will display No of Male, Female and Total

Activity icon

Started a new Conversation How To Count All The Gender Fields For Charts

In My Laravel-5.8 project I am count all the gender_id:

$gender_record = HrEmployee::selectRaw('count(gender_id) as count,gender_id, if (gender_id = 1, "Male", "Female") as gender')->where('company_id', $userCompany)->groupBy('gender_id')->get();

Already, I am representing 1 as Male and 2 as Female. How I want to represent all the fields also as "All". So that I will have Male, Female, All.

How do I adjust my query for that?

Thank you.

May
19
1 week ago
Activity icon

Started a new Conversation How To Include API Subscription Key In My Laravel End Point

In my Laravel-5.8, I am trying to consume API end point GET Request with Guzzle:

  use App\Employee;
  use App\Department;

  public function index() 
  {  
      $client = new GuzzleHttp\Client();
       $res = $client->request('GET','https://api.employees.net/allemployees')->getBody();

        $clientdatas = json_decode($res, true);

     ...
  }

The API has subscription key.

In POSTMAN, I did it this way and it works:

GET        https://api.employees.net/allemployees?key=fgfdhsddddDDDDD

How do I add the subscription key to my Laravel api

  public function index() 
  {  
      $client = new GuzzleHttp\Client();
       $res = $client->request('GET','https://api.employees.net/allemployees')->getBody();

        $clientdatas = json_decode($res, true);

     ...
  }

Thank you.

Activity icon

Started a new Conversation How To Get Available_leave_days And Include It In The Current Leave Table In View Blade

I have this code in Laravel-5.8 that displays employee leaves on table in view blade:

Controller:

public function index()
{
    $userCompany    = Auth::user()->company_id;
    $userID         = Auth::user()->id;
    $userEmployee = Auth::user()->employee_id;
    $leaverequests = HrLeaveRequest::where('employee_id', $userEmployee)->where('company_id', $userCompany)->orderBy('created_at', 'desc')->get();
      return view('leaves.index')->with('leaverequests', $leaverequests)           
}

This is rendered on the view blade

view:

        <table class=" table table-bordered table-striped table-hover datatable">
            <thead>
                <tr>

                    <th width="10">
                        #
                    </th>
                    <th>
                        Leave Type
                    </th>
                    <th>
                        Start Date
                    </th>
                    <th>
                        End Date
                    </th>  
                    <th width="18%">
                        &nbsp;
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach($leaverequests as $key => $leaverequest)
                        <td>
                            {{$key+1}}
                        </td>
                        <td>
                            {{isset($leaverequest->leavetype) ? $leaverequest->leavetype->leave_type_name : 'N/A'}}
                        </td>
                        <td>
                            {{Carbon\Carbon::parse($leaverequest->commencement_date)->format('d-m-Y') ?? '' }}                             
                        </td>
                        <td>
                            {{Carbon\Carbon::parse($leaverequest->resumption_date)->format('d-m-Y') ?? '' }} 
                        </td>  
                            
                @endforeach 
            </tbody>
        </table>

This is working perfectly. But I want to insert on the same view blade that displays the available leave days for the employee.

Already I have the query:

$availableleavedays              = DB::table('hr_leave_requests')->select(DB::raw("IFNULL(SUM(no_of_days),0) as no_of_days"))->where('employee_id', $userEmployee)->where('leave_status', 4)->whereYear('created_at', '=', date('Y'))->first();

Since its the same table and Model Class, how do I merge;

$availableleavedays              = DB::table('hr_leave_requests')->select(DB::raw("IFNULL(SUM(no_of_days),0) as no_of_days"))->where('employee_id', $userEmployee)->where('leave_type_id', $request->id)->where('leave_status', 4)->whereYear('created_at', '=', date('Y'))->first();

to the current Query in the Controller:

 $leaverequests = HrLeaveRequest::where('employee_id', $userEmployee)->where('company_id', $userCompany)->orderBy('created_at', 'desc')->get();

So that my view blade will change to:

        <table class=" table table-bordered table-striped table-hover datatable">
            <thead>
                <tr>

                    <th width="10">
                        #
                    </th>
                    <th>
                        Leave Type
                    </th>
                    <th>
                        Start Date
                    </th>
                    <th>
                        End Date
                    </th>
                    <th>
                        Available Day
                    </th> 
                    <th width="18%">
                        &nbsp;
                    </th>
                </tr>
            </thead>
            <tbody>
                @foreach($leaverequests as $key => $leaverequest)
                        <td>
                            {{$key+1}}
                        </td>
                        <td>
                            {{isset($leaverequest->leavetype) ? $leaverequest->leavetype->leave_type_name : 'N/A'}}
                        </td>
                        <td>
                            {{Carbon\Carbon::parse($leaverequest->commencement_date)->format('d-m-Y') ?? '' }}                             
                        </td>
                        <td>
                            {{Carbon\Carbon::parse($leaverequest->resumption_date)->format('d-m-Y') ?? '' }} 
                        </td>  
                        <td>
                            {{isset($leaverequest->available_days) ? $leaverequest->available_days : 'N/A'}}
                        </td>
                            
                @endforeach 
            </tbody>
        </table>

hr_leave_requests is the table and the model class is HrLeaveRequest

Thank you

Activity icon

Replied to #message: "SQLSTATE[42S22]: Column Not Found: 1054 Unknown Column '1' In 'on Clause' (SQL:

@michaloravec - Thanks.

->where('hr_leave_requests.employment_type_id', $employmentTypeId)

suppose to be

->where('hr_leave_type_details.employment_type_id', $employmentTypeId)

but the error is still there

Activity icon

Replied to #message: "SQLSTATE[42S22]: Column Not Found: 1054 Unknown Column '1' In 'on Clause' (SQL:

@michaloravec - This is the structure

class HrLeaveType extends Model
{
    protected $table = 'hr_leave_types';

    protected $fillable = [
      'id',
          'leave_type_name',
      ];

    public function leavetypedetail()
    {
      return $this->hasMany('App\Models\LeaveTypeDetail');
    }  
}

class HrLeaveTypeDetail extends Model
{
    protected $table = 'hr_leave_type_details';
    protected $fillable = [
          'id',
          'leave_type_id',
          'employment_type_id',
          'no_of_days',
      ];

    public function leavetype()
    {
        return $this->belongsTo('App\Models\HrLeaveType', 'leave_type_id', 'id');
    } 

    public function employmenttype()
    {
        return $this->belongsTo('App\Models\HrEmploymentType', 'employment_type_id', 'id' );
    }    
}

class HrLeaveRequest extends Model
{
    protected $table = 'hr_leave_requests';
    protected $fillable = [
          'id',
          'employee_id',
          'leave_type_id',
          'leave_status',
          'no_of_days',
      ];


    public function employee()
    {
        return $this->belongsTo('App\Models\HrEmployee','employee_id');
    }    

    public function leavetype()
    {
       return $this->belongsTo('App\Models\LeaveType','leave_type_id');
    }
}
  1. All the leave_type_name in LeaveType must be load (That's why I use left join)
  2. all the no_of_days relating to employment_type_id of the employee must be loaded

This is what I'm trying to achieve.

https://i.stack.imgur.com/KNuin.png

If there is no field/value for $approvedLeaves, it should initialize with 0

Activity icon

Replied to #message: "SQLSTATE[42S22]: Column Not Found: 1054 Unknown Column '1' In 'on Clause' (SQL:

@michaloravec - How please? I have been on this for long. I have tried other methods. This is the one that work so far. Kindly assist.

Activity icon

Replied to #message: "SQLSTATE[42S22]: Column Not Found: 1054 Unknown Column '1' In 'on Clause' (SQL:

@michaloravec - When I changed the code to:

    $all = DB::table('hr_leave_type_details')
    ->leftJoin('hr_leave_types', function($join) use ($employmentTypeId, $userCompany, $userEmployee)
    {
        $join->on('hr_leave_types.id', '=', 'hr_leave_type_details.leave_type_id')
        ->where('hr_leave_type_details.employment_type_id', $employmentTypeId)
                ->where('hr_leave_types.company_id','=', $userCompany);

    })
    ->leftJoin('hr_leave_requests', function($join) use ($employmentTypeId, $userCompany, $userEmployee)
    {
        $join->on('hr_leave_requests.employee_id', '=', $userEmployee)
        ->where('hr_leave_requests.employment_type_id', $employmentTypeId)
                ->where('hr_leave_requests.leave_status',4);   

    })
    ->groupBy('leave_requests.employee_id', 'hr_leave_requests.leave_type_id')

    ->select('hr_leave_type_details.no_of_days','hr_leave_requests.employee_id','hr_leave_requests.leave_type_id', DB::raw('SUM(hr_leave_requests.no_of_days) AS approvedLeave'),DB::raw('SUM(hr_leave_requests.no_of_days) - hr_leave_type_details.no_of_days  AS availableleaves'))
        ->get();

I got this new error:

#message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column '17' in 'on clause' (SQL: select hr_leave_type_details.no_of_days, hr_leave_requests.employee_id, hr_leave_requests.leave_type_id, SUM(hr_leave_requests.no_of_days) AS approvedLeave, SUM(hr_leave_requests.no_of_days) - hr_leave_type_details.no_of_days AS availableleaves from hr_leave_type_details left join hr_leave_types on hr_leave_types.id = hr_leave_type_details.leave_type_id and hr_leave_type_details.employment_type_id = 1 and hr_leave_types.company_id = 1 left join hr_leave_requests on hr_leave_requests.employee_id = 17 and hr_leave_requests.employment_type_id = 1 and hr_leave_requests.leave_status = 4 group by leave_requests.employee_id, hr_leave_requests.leave_type_id) ◀"

The '17' there is from:

hr_leave_requests.employee_id = 17

What do I do?

Activity icon

Started a new Conversation #message: "SQLSTATE[42S22]: Column Not Found: 1054 Unknown Column '1' In 'on Clause' (SQL:

I have this query in my Laravel-5.8 Controller:

    $userCompany = Auth::user()->company_id;
    $userId = Auth::user()->id;     
    $userEmployee = Auth::user()->employee_id;
    $employmentTypeId = HrEmployee::where('id', $userEmployee)->where('is_active', 1)->first()->employment_type_id; 

    $all = DB::table('hr_leave_type_details')
    ->leftJoin('hr_leave_types', function($join) use ($employmentTypeId, $userCompany, $userEmployee)
    {
        $join->on('hr_leave_types.id', '=', 'hr_leave_type_details.leave_type_id');
        $join->on('hr_leave_type_details.employment_type_id', $employmentTypeId);
        $join->on('hr_leave_types.company_id','=', $userCompany);

    })
    ->leftJoin('hr_leave_requests', function($join) use ($employmentTypeId, $userCompany, $userEmployee)
    {
        $join->on('hr_leave_requests.employee_id', '=', $userEmployee);
        $join->on('hr_leave_requests.employment_type_id', $employmentTypeId);
        $join->on('hr_leave_requests.leave_status',4);

    })
    ->groupBy('leave_requests.employee_id', 'hr_leave_requests.leave_type_id')

    ->select('hr_leave_type_details.no_of_days','hr_leave_requests.employee_id','hr_leave_requests.leave_type_id', DB::raw('SUM(hr_leave_requests.no_of_days) AS approvedLeave'),DB::raw('SUM(hr_leave_requests.no_of_days) - hr_leave_type_details.no_of_days  AS availableleaves'))
        ->get();

When I ran the Code, I got this error:

#message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'on clause' (SQL: select hr_leave_type_details.no_of_days, hr_leave_requests.employee_id, hr_leave_requests.leave_type_id, SUM(hr_leave_requests.no_of_days) AS approvedLeave, SUM(hr_leave_requests.no_of_days) - hr_leave_type_details.no_of_days AS availableleaves from hr_leave_type_details left join hr_leave_types on hr_leave_types.id = hr_leave_type_details.leave_type_id and hr_leave_type_details.employment_type_id = 1 and hr_leave_types.company_id = 1 left join hr_leave_requests on hr_leave_requests.employee_id = 17 and hr_leave_requests.employment_type_id = 1 and hr_leave_requests.leave_status = 4 group by leave_requests.employee_id, hr_leave_requests.leave_type_id) ◀"

How do I resolve it? And where is '1' coming from?

Thank you.

Activity icon

Replied to [2020-05-19 11:43:11] Production.ERROR: Undefined Variable: EmploymentTypeId {"userId":2,"exception":"[object] (ErrorException(code: 0)

@michaloravec - Yes. I have been using this in all the codes and it works:

    $userCompany = Auth::user()->company_id;
    $userId = Auth::user()->id;     
    $userEmployee = Auth::user()->employee_id;
Activity icon

Started a new Conversation [2020-05-19 11:43:11] Production.ERROR: Undefined Variable: EmploymentTypeId {"userId":2,"exception":"[object] (ErrorException(code: 0)

In my Laravel-5.8 I have this code in the controller:

$userId = Auth::user()->id;
$userCompany = Auth::user()->company_id;
$employmentTypeId = HrEmployee::where('id', $userEmployee)->where('is_active', 1)->first()->employment_type_id;

$all = DB::table('leave_category_details')
 ->leftJoin('leave_categories', function($join)
{
  $join->on('leave_categories.id', '=', 'leave_category_details.leave_category_id');
  $join->on('leave_categories.employment_category_id',$employmentTypeId);
  $join->on('leave_categories.company_id','=', $userCompany);

})
->leftJoin('leave_requests', function($join)
{
   $join->on('leave_requests.employee_id', '=', $userId);
   $join->on('leave_requests.leave_category_id', $employmentTypeId);
   $join->on('leave_status',4);

})
->groupBy('leave_requests.employee_id', 'leave_requests.leave_category_id')
 ->select('leave_category_details.no_of_days','leave_requests.employee_id','leave_requests.leave_category_id', DB::raw('SUM(leave_requests.approved_days) AS approvedLeave'),DB::raw('SUM(leave_requests.approved_days) - leave_category_details.no_of_days  AS availableleaves')
  ->get();

When I ran the code, I got this error:

[2020-05-19 11:43:11] production.ERROR: Undefined variable: employmentTypeId {"userId":2,"exception":"[object] (ErrorException(code: 0)

[2020-05-19 11:43:11] production.ERROR: Undefined variable: userCompanyd {"userId":2,"exception":"[object] (ErrorException(code: 0)

Why?

These variables are declared.

How do I resolve it? Thank you

Activity icon

Replied to How To Generate Leave Balance Table For A Particular Employee

@flightsimmer668 - Please I don't understand this.

    $i['applicable_leaves'] = // applicable leaves for this category
$i['approved_leaves'] = // approved leaves for this category
$i['available_leaves'] = // available leaves for this category

Can you explain a bit, maybe with example.

Thank you

May
18
1 week ago
Activity icon

Started a new Conversation How To Generate Leave Balance Table For A Particular Employee

In my Laravel-5.8 project, when an employee logs in I want to display a table as shown below that shows his Leave Balance

https://i.stack.imgur.com/KNuin.png

I have 3 tables that are applicable

class LeaveCategory extends Model
{
   protected $table = 'leave_categories';

   protected $fillable = [
              'leave_category_name',
          ];

   public function leavecategorydetail()
   {
       return $this->hasMany('App\Models\LeaveCategoryDetail');
   }  
}

class LeaveCategoryDetail extends Model
{
   protected $table = 'leave_category_details';
   protected $fillable = [
              'id',
              'leave_category_id',
              'employment_type_id',
              'no_of_days',
          ];

   public function leavecategory()
   {
       return $this->belongsTo('App\Models\LeaveCategory', 'leave_category_id', 'id');
   }

   public function employmenttype()
   {
       return $this->belongsTo('App\Models\EmploymentType', 'employment_type_id', 'id' );
   }    
}

class LeaveRequest extends Model
{
   protected $table = 'leave_requests';
   protected $fillable = [
              'id',
              'employee_id',
              'leave_category_id',
              'leave_status',
              'approved_days',
          ];


   public function employee()
   {
       return $this->belongsTo('App\Models\Employee','employee_id');
   }    

   public function leavetype()
   {
       return $this->belongsTo('App\Models\LeaveCategory','leave_category_id');
   }
}

As earlier said, the expected result is to have 4 columns (Leave Category , Applicable Leave, Approved Leave , Available )

Controller

public function leave_balance()
{
    $userId = Auth::user()->id;
$userCompany = Auth::user()->company_id;
$employmentcategory = Employee::select('employeement_category_id')->where('employee_id', $userId)->where('is_active', 1)->first();

//Leave Category
$leavecategories = LeaveCategory::select('leave_category_name')->where('company_id', $userCompany)->get();

//Applicable Leave
    $applicableleaves = DB::table('leave_categories')
             ->join('leave_category_details', 'leave_category_details.leave_category_id', '=', 'leave_categories.id')
             ->select('leave_category_details.no_of_days')
             ->where('leave_categories.company_id', $userCompany)
             ->where('leave_categories.employment_category_id',$employmentcategory)
             ->get(); 

//Approved Leave
    $approvedleaves = DB::table('leave_requests')
             ->select('employee_id','leave_category_id', DB::raw('SUM(approved_days) AS approvedLeave'))
             ->where('employee_id', $userId)
	 ->where('leave_category_id', $employmentcategory)
             ->where('leave_status',4)
             ->groupBy('employee_id', 'leave_category_id')
             ->get(); 

//Available
$availableleaves = $applicableleaves - $approvedleaves

   $leavebalances = ...

return view('leave-balances')
	->with('leavebalances', $leavebalances)
}

How do I combine the four queries in my controller ($leavecategories, $applicableleaves, $approvedleaves, $availableleaves) into $leavebalances and also get a view like

https://i.stack.imgur.com/KNuin.png

            <thead>
                <tr>
                    <th width="55%">
                        Leave Category
                    </th>
                    <th width="15%">
                        Applicable Leave
                    </th>
                    <th width="15%">
                        Approved Leave
                    </th>
                    <th width="15%">
                        leavebalances
                    </th>                        
                </tr>
            </thead>
            <tbody>      
                <!--start foreach-->
                    <td>

                    </td> 
                    <td>

                    </td>      
                    <td>

                    </td> 
                    <td>

                    </td>                           
                <!--end foreach-->

If there is no field/value for $approvedleaves, it should initialize with 0

Thank you.

May
17
1 week ago
Activity icon

Started a new Conversation Prevent Submit Until All Employee Comments Are Filled

I have project approval application. The employee can can for more than one project at a time. I have successfully written the code for project application, where the employee apply for projects.

Model

class Project extends Model
{
    protected $table = 'projects';

    protected $fillable = [
              'id',
              'employee_id',
              'manager_id',
              'is_approved',
              'project_title',
          ]; 

   public function projectcomment(){
     return $this->hasMany('App\Models\ProjectComment');
   } 

    public function employee()
    {
      return $this->belongsTo('App\Models\HrEmployee','employee_id');
    }  

}

class ProjectComment extends Model
{
   protected $table = 'project_comments';

   protected $fillable = [
              'id',
              'project_id',
              'manager_comment',

          ];

   public function project()
   {
     return $this->belongsTo('App\Models\Project','project_id');
   }   
}

Controller

public function manager_employee_all_project_approve(Request $request, $id)
{
    $userCompany = Auth::user()->company_id;
    $userEmployee = Auth::user()->employee_id;    
    $userId = Auth::user()->id;
    $employeeids = DB::table('hr_employees')->select('id')->where('id', $employee->id)->first();
    $employeeid = $employeeids->id;        
    
    $approved_count = Project::where('employee_id', $id)->count();
    if ($approved_count > 0){

DB::beginTransaction(); try { $approved_post = Project::where('employee_id', $id)->where('is_approved','!=', 3) ->update([ 'is_approved' => 2 ]); }

view

    <div class="row no-print">
        <div class="col-12">
          @if ($incompleteCount)
              <a href ="{{ route('projects.manager_employee_all_project_approve', ['id' => $project->employee_id])}}" class="btn btn-primary float-left"><i class="fas fa-check"></i> Approve</a>
         
          @endif 
        </div>       
    </div> 

The manager adds comment on each of the project before he approves the project.

The comment field (manager_comment) is in another table, project_comments. From the Controller above, the manager approves the project (projects) by clicking on submit button and then is_approved is set to 2 (2 is for approve).

However, if the manager has not added comment (manager_comment in project_comments relating to project_id and employee_id), the application should prevent him from clicking the submit button. How do I achieve this?

Thank you.

May
15
2 weeks ago
Activity icon

Started a new Conversation How To Also Display Percentage Aside Number In Laravel ChartJs Donut

In my Larave-5.8, I am trying to generate Donut chart using:

public function report()
{
    $userCompany = Auth::user()->company_id;

    $record = HrEmployee::selectRaw('count(gender_id) as count,gender_id, if (gender_id = 1, "Male", "Female") as gender')->where('company_id', $userCompany)->groupBy('gender_id')->get();        
    $data = [];

    foreach($record as $row) {
       $data['label'][] = $row->gender;
       $data['data'][] = (int) $row->count;
     }

   $data['chart_data'] = json_encode($data);        
    
    return view('report-default', $data);       
}

View

          <div class="card-body">
            <canvas id="empGender" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas>
          </div>

    <script>
      $(function () {
        /* ChartJS
         * -------
         * Charts using ChartJS
         */

       //-------------
       //- DONUT CHART -
       //-------------
       // Get context with jQuery - using jQuery's .get() method.
    var cData = JSON.parse(`<?php echo $chart_data; ?>`);
    var donutChartCanvas = $('#empGender').get(0).getContext('2d')
    var donutData        = {
      labels: [
          'Male', 
          'Female',
      ],
      datasets: [
        {
        data: cData.data,
          backgroundColor : [
              '#f56954', 
              '#00a65a', 
          ],
                borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
            ],
            borderWidth: 1          
         }  
      ]
    }
    var donutOptions     = {
      maintainAspectRatio : false,
      responsive : true,
    }
    //Create pie or douhnut chart
    // You can switch between pie and douhnut using the method below.
     var donutChart = new Chart(donutChartCanvas, {
      type: 'doughnut',
      data: donutData,
      options: donutOptions      
     })

    })   
    </script> 

At the moment, I have successfully created the Donut that it displays the number of males and Females. But I also want to display the percentage of each.

How do I achieve this?

Thanks

Activity icon

Started a new Conversation How To Use My Query To Represent 1 As Male And 2 As Female

In my Larave-5.8, I am trying to generate bar chart using:

public function report()
{
    $userCompany = Auth::user()->company_id;
    $userId = Auth::user()->id;   

     $gender_datas = HrEmployee::selectRaw('count(gender_id) as count,gender_id')->where('company_id', $userCompany)->groupBy('gender_id')->get();
     $data=array();
     foreach ($gender_datas as $result) {
         $data[$result->gender_id]=(int)$result->count;
     }
    
    return view('report-default')
            ->with('data', $data);     
}

View

<div id="piechart_3d" style="width: 650px; height: 450px;"></div>


<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
  google.charts.load("current", {packages:["corechart"]});
  google.charts.setOnLoadCallback(drawChart);
  function drawChart() {

   var record={!! json_encode($data) !!};
   console.log(record);
   // Create our data table.
   var data = new google.visualization.DataTable();
    data.addColumn('string', 'Gender');
   data.addColumn('number', 'Total_Signup');
   for(var k in record){
        var v = record[k];
       
         data.addRow([k,v]);
      console.log(v);
      }
    var options = {
      title: 'Gender Classification',
      is3D: true,
    };
    var chart = new google.visualization.PieChart(document.getElementById('piechart_3d'));
    chart.draw(data, options);
  }
</script>    

From the table table, gender_id is an integer field. 1=Male and 2=Female.

In my Chart it is displaying 1 and 2.

I want it to display 1 as male and 2 as female.

How do I use my Query to represent 1 as Male and 2 as Female

How do I achieve this?

Thank you

May
14
2 weeks ago
Activity icon

Started a new Conversation Uncaught SyntaxError: Unexpected Identifier In Laravel Google Charts API

In my Laravel-5.8, I am trying to apply Google chart API to Draw Pie char for male and female employees

Controller:

public function report()
{

    $data = DB::table('hr_employees')
        ->select(
                DB::raw('gender_id as gender'),
                DB::raw('count(*) as number')
                )
        ->groupBy('gender') 
        ->get();   
    $array[] = ['Gender', 'Number'];
    
    foreach($data as $key => $value) 
    {
        $array[++$key] = [$value->gender, (int)$value->number];
    }        
    
    return view('report-default')
            ->with('gender', json_encode($array));                 
   
}

view

            <div id="pie_chart" style="width:750px; height:450px;">

            </div>

<script src="{{ asset('theme/adminlte3/plugins/jquery/jquery.min.js') }}"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<script type="text/javascript">
    var analytics = <?php echo $gender; ?>
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart()
    {
     var data = google.visualization.arrayToDataTable(analytics);
     var options = {
      title : 'Percentage of Male and Female Employee',
      sliceVisibilityThreshold: 0.000000001,
      pieHole: 0.4
     };
     var chart = new google.visualization.PieChart(document.getElementById('pie_chart'));
     chart.draw(data, options);
    }
 </script>

When I ran the application, I got this error:

report-default:814 Uncaught SyntaxError: Unexpected identifier

and this line of code is marked red:

google.charts.load('current', {'packages':['corechart']});

  1. How do I resolve it?

  2. When gender_id (gender) is 1 I want it to display Male and 2 for Female.

Thank you

Activity icon

Replied to How To Prevent Reload Of A Page On Form Submit

@michaloravec - When I remove that it didn't load data into the table again:

   <span class="font-weight-bold">
        For: <span id="employee_name"></span>
    </span>

Please note that the javascript :

<script type="text/javascript">
 $(document).ready(function() {
 $(document).on('change', '#employee_id', function() {
    var air_id =  $(this).val();

    var a = $(this).parent();
   var op = "";

  $.ajax({
     type: 'GET',
     url: '{{ route('get.employee.all') }}',
     data: { 'id': air_id ,'_token':'{{ csrf_token()}}'},
     dataType: 'json',
     success: function(data) {
        console.log(data);
         $('#employee_name').html(data.fullname);
         },
      error:function(){
        }
      });
     });
  });
</script>

is only for:

   <span class="font-weight-bold">
        For: <span id="employee_name"></span>
    </span>
Activity icon

Replied to How To Prevent Reload Of A Page On Form Submit

@michaloravec - I'm so sorry, how did you say I should re-write this:

<script type="text/javascript">
 $(document).ready(function() {
 $(document).on('change', '#employee_id', function() {
   var air_id =  $(this).val();

   var a = $(this).parent();
   var op = "";

  $.ajax({
    type: 'GET',
    url: '{{ route('get.employee.all') }}',
    data: { 'id': air_id ,'_token':'{{ csrf_token()}}'},
    dataType: 'json',
    success: function(data) {
        console.log(data);
         $('#employee_name').html(data.fullname);
         },
    error:function(){
    }
     });
   });
  });
</script>
Activity icon

Started a new Conversation How To Prevent Reload Of A Page On Form Submit

In my Laravel-5.9, I use a dropdown on change to load employee leave details on a table and also to display the fullname of that particular employee.

Controller

public function leave_review(Request $request)
{

try {  
$userEmployee               = Auth::user()->employee_id;
    $leavemanagers               = null;
    $managerEmployeeId          = DB::table('hr_employees')->select('id')->where('manager_id', $userEmployee)->pluck('id');
    $managerfilters             = HrEmployee::where('company_id', $userCompany)->whereIn('id', $managerEmployeeId)->where('is_active', 1)->get();
    
    if (Auth::user()->hasRole('Manager')) 
    {
        if($request->filled(['employee_id']))  
        {
            $leavemanagers = Leave::where('is_published', 1)
                ->when($request->input('employee_id'), function ($query) use ($request) {
                $query->where('employee_id', $request->input('employee_id'));
        })
        ->get();                        
        }else
        {
            $leavemanagers = Leave::where('is_active', 0)->get();
        }
    }

    return view('admin.leaves.leave_review')
                ->with('leavemanagers', $leavemanagers)
                ->with('managerfilters', $managerfilters); 
    } catch (Exception $exception) {
        Session::flash('error', 'Action failed! Please try again');
        return back();
        }                     
}

public function findEmployee(Request $request){
   $data =  HrEmployee::select(DB::raw('CONCAT(employee_code, " - ", first_name, " ", last_name) AS full_name'))->where('id', $request->id)->first();

 return response()->json($data);
}

route/web.php

Route::get('admin/leaves/leave_review', '[email protected]_review')->name('admin.leaves.leave_review');
Route::get('get/findEmployee','[email protected]')->name('get.employee.all');

view

       <span class="font-weight-bold">
            For: <span id="employee_name"></span>
        </span>

<div class="card-body">
    
                
                <form action="{{ route('admin.leaves.leave_review') }}">
                 <div class="row">   
                    
          <div class="col-sm-4">
            <div class="form-group">
                <span id="employee_name"></span>
            </div>
          </div>   
          <div class="col-sm-4">
            <div class="form-group">
            </div>
          </div>   
            
          <div class="col-sm-4">
            <div class="form-group" method = "get">
                <select class="form-control select2bs4" data-placeholder="Select Employees tabindex="1" id="employee_id" name="employee_id" onchange="this.form.submit()">
                    <option value="select">Select Employees</option>
                @foreach($managerfilters as $managerfilter)
                    <option value="{{ $managerfilter->id }}" {{ request()->input('employee_id') == $managerfilter->id ? 'selected' : '' }}>{{ $managerfilter->employee_code }} - {{ $managerfilter->first_name }} {{ $managerfilter->last_name }}</option>
                @endforeach
                 </select>
            </div>
          </div>   

    </div>
        </form>

    
    <div class="table-responsive">
        <table class=" table table-bordered table-striped table-hover datatable">
            <thead>
                <tr>
                    <th>
                        Leave Type
                    </th>
                    <th>
                        Leave Name
                    </th>
                </tr>
            </thead>
            <tbody>                    
                @foreach($leavemanagers as $key => $leavemanager)
                <tr>
                        <td>
                            {{$leavemanager->leave_type ?? '' }}
                        </td>                           
                        <td>
                            {{$leavemanager->leave_name ?? '' }}
                        </td>                                                         
                </tr>
                @endforeach 
            </tbody>
        </table>
    </div>                   
    </div>

<script type="text/javascript">
 $(document).ready(function() {
 $(document).on('change', '#employee_id', function() {
    var air_id =  $(this).val();

    var a = $(this).parent();
    var op = "";

  $.ajax({
        type: 'GET',
        url: '{{ route('get.employee.all') }}',
        data: { 'id': air_id ,'_token':'{{ csrf_token()}}'},
        dataType: 'json',
        success: function(data) {
            console.log(data);
             $('#employee_name').html(data.fullname);
             },
        error:function(){
        }
      });
     });
  });
</script>

When I click on the select dropdown, on change I expected it to displays the fullname of the select employee:

       <span class="font-weight-bold">
            For: <span id="employee_name"></span>
        </span>

and also leave details of the selected employee on:

<table class=" table table-bordered table-striped table-hover datatable">
...
</table>

as shown in the code above.

The leave details displays very well on the table. But for the employee fullname which uses the json to jquery, when I click on the dropdown it displays it but the page quickly reloads to load the table. So in doing that, it quickly clears the content of:

       <span class="font-weight-bold">
            For: <span id="employee_name"></span>
        </span>

and there is nothing there.

How do I resolve that?

Thank you.

May
13
2 weeks ago
Activity icon

Replied to How To Load Employee Name Based On Dropdown Change

@ramjithap - When I click on the select dropdown, on change it displays the result of:

For: <span id="employee_name"></span>

But as soon as the page finish loading, it clears off.

Why? How do I resolve that?

Thank you.

May
12
2 weeks ago
Activity icon

Replied to How To Load Employee Name Based On Dropdown Change

What's the right way of presenting the result:

I want to do something like this:

                <span class="font-weight-bold">
                    For: 
                    {{$leave->employee->fullname ?? '' }}
                </span>

This is what I'm having and it's very odd.

                <span class="font-weight-bold">
                    For: 
                    <input id="employee_name" class="form-control" value="" readonly>
                </span>
May
11
2 weeks ago
Activity icon

Started a new Conversation How To Load Employee Name Based On Dropdown Change

In my Laravel project I want to load employee fullname based on dropdown change of the selected employee.

Controller:

   public function findEmployee(Request $request){
     $data =  HrEmployee::select(DB::raw('CONCAT(employee_code, " - ", first_name, " ", last_name) AS full_name'))->where('id', $request->id)->get()->pluck('full_name');

    return response()->json($data);

  }

route/web.php

Route::get('get/findEmployee','[email protected]')->name('get.employee.all');

view

          <div class="col-sm-4">
            <div class="form-group" method = "get">
                <select class="form-control select2bs4" data-placeholder="Select Employees tabindex="1" id="employee_id" name="employee_id" onchange="this.form.submit()">
                    <option value="select">Select Employees</option>
                @foreach($managerfilters as $managerfilter)
                    <option value="{{ $managerfilter->id }}" {{ request()->input('employee_id') == $managerfilter->id ? 'selected' : '' }}>{{ $managerfilter->employee_code }} - {{ $managerfilter->first_name }} {{ $managerfilter->last_name }}</option>
                @endforeach
                 </select>
            </div>
          </div>   

javascript

   <script type="text/javascript">
    $(document).ready(function() {
        $(document).on('change', '#employee_id', function() {
            var air_id =  $(this).val();

            var a = $(this).parent();
            var op = "";
            
            $.ajax({
                type: 'get',
                url: '{{ route('get.employee.all') }}',
                data: { 'id': air_id },
                dataType: 'json',      //return data will be json
                success: function(data) {
                    console.log(data);
 
                     $('#employee_name').val(data);
                     },
                error:function(){

                }
            });
        });
    });
    </script>

On dropdownlist change, I expected to see the full_name of the selected employee on

               <span class="font-weight-bold">
                    For: <input id="employee_name" class="form-control" value="" readonly>

                </span>

but I got this error:

HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE

How do I resolve it?

Thanks

Activity icon

Awarded Best Reply on Why Is My Route Repeating A Folder In The Route Twice

@michaloravec - When I did as you advised and use

Route::group(['prefix' => 'admin', 'as' => 'admin.', 'namespace' => 'Admin', 'middleware' => ['auth']], function () {
   Route::get('leaves/leave_review', '[email protected]_review')->name('leaves.leave_review');
});

I error 404 page not found and the uri still remain as:

http://localhost:8888/hrm/admin/admin/leaves/leave_review