noblemfd

noblemfd

Member Since 7 Months Ago

Experience Points
22,740
Total
Experience

2,260 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 5
22,740 XP
Aug
04
1 day ago
Activity icon

Started a new Conversation How To Display Unknown On The View Blade For Date_of_birth

In my Laravel-5.8, I have this code:

protected $fillable = [
              'id',
              'first_name',
               'last_name',
              'date_of_birth',

          ];

protected $dates = [
      'date_of_birth',
  ];

public function setDateOfBirthAttribute($value)
{
    $this->attributes['date_of_birth'] = Carbon::createFromFormat('d-m-Y', $value);
}

public function getDateOfBirthAttribute($input)
{
   return Carbon::parse($input)->format(config('app.date_format'));   
}

config/app.php

    'date_format' => 'd/m/Y',
    'date_format_js' => 'dd/mm/yy', 

view

 <div class="col-md-4">
    <p for="">: {{ $employee->date_of_birth }} </p>
 </div

Whenever the date_of_birth field is null in the database, the application displays today's date on the view blade for the date of birth:

04/08/2020

How do I display "Unknown" on the view blade for date_of_birth whenever the date_of_birth is null?

Thanks

Activity icon

Started a new Conversation Syntax Error Or Access Violation: 1055 'laravelapp.ltd.no_of_days' Isn't In GROUP BY

In my Laravel-5.8 project, I am developing employee leave application. In the application, in a particular year, each employee can apply for different leaves. when an employee logs in I want to display a table as shown below that shows Leave Balance of each leave type name of the logged in user

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

I have 3 tables that are applicable

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 employeetype()
   {
       return $this->belongsTo('App\Models\HrEmployeeType', 'employee_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\HrLeaveType','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;
    $leaveBalance = DB::table('hr_leave_types AS lt')
                ->leftJoin('hr_leave_type_details AS ltd', function($join) use ($userCompany)
                    {
                        $join->on('ltd.leave_type_id', '=', 'lt.id')
                        ->where('ltd.company_id', '=', $userCompany);
                    })
                ->leftJoin('hr_leave_requests AS lr', function($join) use ($userCompany, $userEmployee)
                    {
                        $join->on('lr.leave_type_id', '=', 'lt.id')
                        ->where('lr.company_id', '=', $userCompany)
                        ->where('lr.employee_id', '=', $userEmployee)
                        ->whereYear('lr.commencement_date', '=', date('Y'))
                        ->where('lr.leave_status', 4);
                    })                        
                ->leftJoin('hr_employees AS e', function($join) use ($userCompany, $userEmployee)
                    {
                        $join->on('e.id', '=', 'lr.employee_id')
                        ->where('e.company_id', '=', $userCompany)
                        ->where('e.id', '=', $userEmployee)
                        ->where('e.employee_type_id', '=', 'ltd.employee_type_id');
                    })  
                ->where('lt.company_id', '=', $userCompany)
                ->select(
                        'lt.leave_type_name as leaveCategory',
                        'ltd.no_of_days as applicableLeave',
                        DB::raw("IFNULL(SUM(lr.no_of_days),0) as approvedLeave")
                       )
                  ->groupBy('lt.leave_type_name', 'e.id')
                ->get();                    

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

available = applicableLeave - approvedLeave

I want to achieve this result

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

When I tried to run the controller, I got this error:

#message: "SQLSTATE[42000]: Syntax error or access violation: 1055 'laravelapp.ltd.no_of_days' isn't in GROUP BY (SQL: select lt.leave_type_name as leaveCategory, `l ▶"

There is no way I can group by 'no_of_days'

I only want to group by leave_type_name and employee_id (e.id)

How do I resolve this?

Thanks

Activity icon

Replied to Store Eloquent Master Detail On Same Page

@michaloravec - Kindly pardon me, if I want to do the same thing for update, how do I go about that

class OrderController extends Controller
{
  public function update(Request $request, $id)
  {
     $order = new Order::findOrFail($id);
     $order->name = $request->order;
     $order->save();


    return redirect("order/{$order->id}")->with('message', 'Order updateded Successfully');
  }
}
Aug
03
2 days ago
Activity icon

Replied to Store Eloquent Master Detail On Same Page

@jlrdw - What you have shown me is get request. It's not posting anything to the database. I need Master detail dynamic data input. Thanks

Activity icon

Replied to [2020-08-02 20:27:38] Production.ERROR: A Two Digit Day Could Not Be Found

@geordiejackson - I use the setDateOfBirth for the datepicker.

When I removed "None" from

   return is_null($input) ? "None" : Carbon::parse($input)->format(config('app.date_format'));   

The error did not come up again, but if the date_of_birth field in the database is null, it displays today's date on the system

Activity icon

Started a new Conversation Store Eloquent Master Detail On Same Page

I have two models,blade page and controllers I have for implementing the master-detail page in Laravel-5.8. I would like to know how I can store detail part to database.

Master Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order  extends Model
{
    protected $fillable = [
        'id',
        'name',
      ];

public function detail()
{
    return $this->hasMany('App\OrderDetail','order_id','id');
}   

Detail Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class OrderDetail extends Model
{
   protected $fillable = [
        'id',
        'order_id',
        'item',
        'total',
    ];
}

create.blade view

     <div class="row">
         <div class="clearix"></div>
        <div class="col-md-12">
            <div class="tile">
                <h3 class="tile-title">Order</h3>
                <div class="tile-body">
                    <form  method="POST" action="{{route('order.store')}}">
                        @csrf
                        <div class="form-group col-md-8">
                            <label class="control-label">Name</label>
                            <input name="name" class="form-control @error('name') is-invalid @enderror" type="text" placeholder="Enter Name">
                            @error('name')
                            <span class="invalid-feedback" role="alert">
                                    <strong>{{ $message }}</strong>
                                </span>
                            @enderror
                        </div>

                    <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th scope="col">Item Name</th>
                            <th scope="col">Total</th>
                            <th scope="col"><a class="addRow"><i class="fa fa-plus"></i></a></th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr>
                            <td><input type="text" name="item[]" class="form-control qty" ></td>
                            <td><input type="text" name="total[]" class="form-control price" ></td>
                            <td><a   class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>
                         </tr>
                        </tbody>
                    </table>

                        <div>
                            <button class="btn btn-primary" type="submit">Submit</button>
                        </div>
                 </form>
                </div>
            </div>

@endsection



<script type="text/javascript">
    $(document).ready(function(){
        $('.addRow').on('click', function () {
            addRow();

        });

        function addRow() {
            var addRow = '<tr>\n' +
'                                <td><input type="text" name="item[]" class="form-control item" ></td>\n' +
'                                <td><input type="text" name="total[]" class="form-control total" ></td>\n' +
'                                <td><a   class="btn btn-danger remove"> <i class="fa fa-remove"></i></a></td>\n' +
 '                             </tr>';
            $('tbody').append(addRow);
        };

        $('.remove').live('click', function () {
            var l =$('tbody tr').length;
            if(l==1){
                alert('you cant delete last one')
            }else{

                $(this).parent().parent().remove();

            }

        });
    });

</script>

Controller

class OrderController extends Controller
{

    public function store(Request $request)
    {
        $order = new Order();
        $order->name = $request->order;
        $order->save();

         return redirect('order/'.$order->id)->with('message','Order created Successfully');
    }
}

I have successfully stored the Order. How do I loop the OrderDetail into it. Both for store and update?

Thanks

Activity icon

Started a new Conversation #message: "Undefined Property: Illuminate\Database\Eloquent\Relations\BelongsTo::$leave_type_name"

In my Laravel-5.8 projects I have two models: HrLeaveType and HrLeaveRequest

Model:

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

    protected $fillable = [
                  'leave_type_name',
                  'no_of_days',
                  'leave_type_code',
              ];


    public function leaverequest(){
        return $this->hasMany('App\Models\Hr\HrLeaveRequest');
    }  
}



class HrLeaveRequest extends Model
{

    protected $table = 'hr_leave_requests';

    protected $primaryKey = 'id';

    protected $fillable = [
                  'id',
                  'employee_id',
                  'department_id',
                   'leave_type_id',
                  'reason',
                  'line_manager_comment',
              ];


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

Employee Make several leave requests.

If the Leave Type is Annual or Annual Leave or annual leave the application should follow the condition in the controller below. But the issue is, we cannot say that the leave_type_id for the Annual Leave will be 1.

HrLeave Type have two fields: id (auto-increment) and leave_type_name (varchar)

id | leave_type_name

1 | Annual Leave

2 | Maternity Leave

3 | Sick Leave

But may not be in this order

Controller

      public function leave_request_approve(Request $request, $id)
      {
         $leaverequest               = HrLeaveRequest::find($id);

        if ($leaverequest->leavetype()->leave_type_name == 'Annual' || $leaverequest->leavetype()->leave_type_name == 'Annual Leave')
        {                                    
            $leaverequest->line_manager_comment    = $request->line_manager_comment;
            $leaverequest->save();
                  
            HrEmployee::where('user_id', $leaverequest->employee_id)->update([
                'on_leave' => 1
            ]);                                                         
            
        }
    }

Since the user can't determine if Annual Leave is carrying the leave_type_id as 1, Instead of

 if ($leaverequest->leave_type_id == 1)

I used

if ($leaverequest->leavetype()->leave_type_name == 'Annual' || $leaverequest->leavetype()->leave_type_name == 'Annual Leave')

When I submitted, I got this error:

#message: "Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$leave_type_name"

How do I resolve it?

Thank you

Aug
02
3 days ago
Activity icon

Started a new Conversation [2020-08-02 20:27:38] Production.ERROR: A Two Digit Day Could Not Be Found

In my Laravel-5.8, I have this code:

protected $fillable = [
              'id',
              'first_name',
               'last_name',
              'date_of_birth',

          ];

protected $dates = [
      'date_of_birth',
  ];

public function setDateOfBirthAttribute($value)
{
    $this->attributes['date_of_birth'] = Carbon::createFromFormat('d-m-Y', $value);
}

public function getDateOfBirthAttribute($input)
{
   return is_null($input) ? "None" : Carbon::parse($input)->format(config('app.date_format'));   
}

config/app.php

    'date_format' => 'd/m/Y',
    'date_format_js' => 'dd/mm/yy', 

view

          <div class="col-12 col-sm-4"> 
            <div class="form-group">  
              <label class="control-label"> Date of Birth:</label>
            <div class="input-group">
                
                <div class="input-group-prepend">
                    <span class="input-group-text"><i class="far fa-calendar-alt"></i></span>
                </div>                                              
                <input type="text" placeholder="dd/mm/yyyy" readonly autocomplete="off" name="date_of_birth" value="{{ Carbon\Carbon::createFromFormat('d/m/Y', $employee->date_of_birth)->format('d-m-Y') }}" class="form-control birthDate">
            </div>     
            </div>  
            <!-- /.form-group -->
          </div>

<script type="text/javascript">
        $(function () {
            $( '.birthDate' ).datepicker({
                dateFormat: 'dd-mm-yy',
                changeMonth: true,
                changeYear: true,  
                maxDate: -1,
                yearRange: "-70:-5",                             
            });

    });
</script>

When I tried to render edit view blade, I got this error:

[2020-08-02 20:27:38] production.ERROR: A two digit day could not be found

If I remove "None" from the getDateOfBirth in the model, but in the index view blade

 <div class="col-md-4">
    <p for="">: {{ $employee->date_of_birth }} </p>
 </div>

it displays today's date when the date is null

How do I get this resolved?

Thanks

Activity icon

Replied to Gender Dropdown Is Not Loading Data On Edit Blade

@thibaultvanc - How do you mean?

I removed:

  <option value="">Select Gender</option>
  <option selected disabled>Select Gender</option>

Yet the problem is still there

Activity icon

Replied to Gender Dropdown Is Not Loading Data On Edit Blade

@thibaultvanc

{{ dd($genders) }}

array:2 [▼ 0 => "Female" 1 => "Male" ]

{{ dd($maritalstatuses) }}

array:6 [▼ 1 => "Single" 2 => "Married" 3 => "Separated" 4 => "Divorced" 5 => "Widow(er)" 6 => "Other" ]

Activity icon

Started a new Conversation Gender Dropdown Is Not Loading Data On Edit Blade

I have this controller:

public $genders = [
    "0" => "Female",
    "1" => "Male",
];

public $maritalstatuses = [
    "1" => "Single",
    "2" => "Married",
    "3" => "Separated",
    "4" => "Divorced",
    "5" => "Widow(er)",
    "6" => "Other",
]; 

public function create()
{
    $designations       =       Designation::all();
     return view('hr.employees.create')
           ->with('designations', $designations)
            ->with('maritalstatuses', $this->maritalstatuses)
            ->with('genders', $this->genders);
}

public function edit($id)
{
     $designations       =       Designation::all();
     $employee = HrEmployee::where('id', $id)->first();
     return view('hr.employees.edit')
	    	->with('designations', $designations)
	->with('maritalstatuses', $this->maritalstatuses)
            ->with('genders', $this->genders);
}

edit view blade

edit.blade

   <form  action="{{route('hr.employees.update', ['id'=>$employee->id])}}" method="post" class="tab-wizard wizard-circle form" enctype="multipart/form-data">
    {{ csrf_field() }}

          <div class="col-12 col-sm-4">
            <div class="form-group">
              <label class="control-label"> Position/Designation:</label>
              <select class="form-control select2bs4" data-placeholder="Choose Position/Designation" tabindex="1" name="employee_designation_id" style="width: 100%;">
                <option value="">Select Position/Designation</option>
                <option selected disabled>Select Position/Designation</option>
                   @if($designations->count() > 0 )
                     @foreach($designations as $designation)
                       <option value="{{$designation->id}}" @if($designation->id == $employee->designation_id) selected @endif>{{$designation->designation_name}}</option>
                     @endforeach
                   @endif
              </select>
            </div>
            <!-- /.form-group -->
          </div>

          <div class="col-12 col-sm-4">
            <div class="form-group">
                <label class="control-label"> Marital Status:</label>
              <select class="form-control select2bs4" data-placeholder="Choose Marital Status" tabindex="1" name="marital_status_id" style="width: 100%;">
                <option value="">Select Marital Status</option>
                <option selected disabled>Select Marital Status</option>
                     @foreach($maritalstatuses as $maritalstatus)
                       option value="{{$k}}" @if($employee->maritalstatus == $k) selected @endif>{{$maritalstatus}}</option>
                     @endforeach
              </select>
            </div>
            <!-- /.form-group -->
          </div>

          <div class="col-12 col-sm-4">
            <div class="form-group">
              <label class="control-label"> Gender:<span style="color:red;">*</span></label>
              <select class="form-control select2bs4" data-placeholder="Choose Gender" tabindex="1" name="gender_code" style="width: 100%;">
                <option value="">Select Gender</option>
                 <option selected disabled>Select Gender</option>
                     @foreach($genders as $k => $gender)
                       option value="{{$k}}" @if($employee->gender == $k) selected @endif>{{$gender}}</option>
                     @endforeach
              </select>
            </div>
            <!-- /.form-group -->
          </div>

The create view blade works perfectly. On the edit view blade, designation is loaded correctly. But for the gender and marital status select dropdown, nothing is loaded.

What is really wrong?

Thanks

Activity icon

Started a new Conversation Option Value Not Visible In Select2 Dropdown

In my Laravel-5.8 I am using Select2 dropdown list

              <select class="form-control select2bs4" data-placeholder="Choose Nationality" tabindex="1" name="nationality_id" style="width: 100%;">
                <option value="">Select Nationality</option>
                     @if($nationalities->count() > 0 )
                     @foreach($nationalities as $nationality)
                       <option value="{{$nationality->id}}">{{$nationality->nationality}}</option>
                     @endforeach
                   @endif
              </select>



    <script>
        $(function () {
          //Initialize Select2 Elements
          $('.select2').select2()

          //Initialize Select2 Elements
          $('.select2bs4').select2({
            theme: 'bootstrap4'
          })
        });
    </script>

It loads the nationalities, but I didn't see this:

<option value="">Select Nationality</option>

in the select2 dropdown?

How do I resolve this?

Thanks

Jul
30
6 days ago
Activity icon

Started a new Conversation Date Field Displays Current Date When It Is Null

In my Laravel-5.8 application, I have a field called hire_date. In the database, the datatype is date and default is NULL.

Model

protected $fillable = [
              'id',
              'employee_code',
              'hire_date',
            ];


 protected $dates = [
     'hire_date',
  ];	

public function setHireDateAttribute($value)
{
    $this->attributes['hire_date'] = Carbon::createFromFormat('d-m-Y', $value);
}
    
public function getHireDateAttribute($input)
{
         return Carbon::parse($input)->format('d-m-Y');
}   

View

<p for="">: {{ $employee->hire_date }} </p>

I want to display None when the date is Null.

But why is it showing today's date (Hire Date 30-07-2020) instead of null?

Thanks

Activity icon

Replied to Production.ERROR: The Separation Symbol Could Not Be Found

@talinon - Yes, I have a field called hire_date. But no selected date in it.

Model

protected $fillable = [
              'id',
              'employee_code',
              'hire_date',
            ];


 protected $dates = [
     'hire_date',
  ];	

public function setHireDateAttribute($value)
{
    $this->attributes['hire_date'] = Carbon::createFromFormat('d-m-Y', $value);
}
    
public function getHireDateAttribute($input)
{
         return Carbon::parse($input)->format('d-m-Y');
}   

View

<p for="">: {{ $employee->hire_date }} </p>

But why is it showing today's date (Hire Date 30-07-2020) instead of null

Activity icon

Replied to Production.ERROR: The Separation Symbol Could Not Be Found

@talinon - This works when I used

{{ $employee->hire_date }}

But it displays today's date when no date is available in the database

How do I resolve it?

Activity icon

Started a new Conversation Production.ERROR: The Separation Symbol Could Not Be Found

In my Laravel-5.8, I am trying to fomat date:

Model

public function setHireDateAttribute($value)
{
    $this->attributes['hire_date'] = Carbon::createFromFormat('d-m-Y', $value);
}
    
public function getHireDateAttribute($input)
{
    return Carbon::createFromFormat('Y-m-d', $input)
      ->format(config('app.date_format'));
}    

View:

<p for="">:{{ Carbon\Carbon::createFromFormat('d/m/Y', $employee->hire_date)->format('d-m-Y') }}</p>

When I rendered the view I got this error:

[2020-07-30 16:42:48] production.ERROR: The separation symbol could not be found Trailing data (View: C:\xampp\htdocs\laravelapp\resources\views\hr\employees\show.blade.php) {"userId":469,"exception":"[object] (ErrorException(code: 0): The separation symbol could not be found

How do I resolve this?

Thanks

Activity icon

Replied to How To Implement Advance Search Filter

@michaloravec - Where do I apply $designationName and $departmentId

Thanks

Jul
29
1 week ago
Activity icon

Started a new Conversation How To Implement Advance Search Filter

I have this code for search filter in my Laravel-5.8 application

Controller

        $render=[];  

            $employees = HrEmployee::where('hr_status', 0);

        $employees=$employees->with('department','designation');
        if(isset($request->first_name))
        {
            $employees=$employees->where('first_name','like','%'.$request->first_name.'%');
            $render['first_name']=$request->first_name;
        }
          if(isset($request->designation_name))
        {
            $employees=$employees->where('designation_name',$request->designation_name);
            $render['designation_name']=$request->designation_name;
        }         
        if(isset($request->department_id))
        {
            $employees=$employees->where('department_id',$request->department_id);
            $render['department_id']=$request->department_id;
        }        
        $employees= $employees->paginate(6);
        $employees= $employees->appends($render);
        $data['employees'] = $employees;  
        $data['departments']= HrDepartment::where('company_id', $userCompany)->pluck('dept_name','id');
        $data['designations']= HrDesignation::where('company_id', $userCompany)->pluck('designation_name','designation_name');

        return view('hr.employees.index',$data);

View

{{ Form::model(request(),['method'=>'get']) }}
    <div class="row" style="margin-bottom: 10px">
    
    <div form-group class="col-sm-3">
        {{Form::label('employee_code', 'Employee No.')}}
        {{ Form::text('employee_code',null,['class'=>'form-control','placeholder'=>'Staff ID']) }}
         
    </div>
    <div class="col-sm-4">
        {{Form::label('department_id', 'Department')}}
        {{ Form::select('department_id',$departments,null,['class'=>'form-control select2bs4','placeholder'=>'Select Department']) }}
    </div>       
    <div class="col-sm-4">
        {{Form::label('designation_name', 'Designation')}}
        {{ Form::select('designation_name',$designations,null,['class'=>'form-control select2bs4','placeholder'=>'Select Designation']) }}
    </div>                 
    
    <div class="col-xs-3">
        <br>
        {{ Form::submit('Search',['class'=>'btn btn-warning']) }}

    </div>
    {{ Form::close() }}
   </div>

Basically, the code above is working perfectly. It filters employees by department, designation and first_name.

However, I want it to extend the first_name to either first_name, middle_name or last_name.

How do I implement something like this into my existing code or any other better way of doing it?

if ($name) {
  $query->where(function($q) use ($name) {
         $q->where('first_name', 'like', "$name%")->orWhere('last_name', 'like', "$name%");
   });
}

Thanks.

Activity icon

Replied to Fields Are Not Being Updated In Cron Jobs

@silencebringer - employee_code and email are unique, but any of the other fields can change at any time: first_name, last_name, other_name and employee_type_code . But what I'm trying to do is that if employee_code and email already exist, the application checks if other fields change then update/edit them.

However, if it's new, it creates everything entirely. But it's throwing error on both create and update.

Thanks

Jul
28
1 week ago
Activity icon

Replied to Fields Are Not Being Updated In Cron Jobs

Hello @silencebringer , when I checked the error Log I got this error:

Next Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'email' (SQL: insert into hr_employees

How do I resolve it?

Activity icon

Replied to Fields Are Not Being Updated In Cron Jobs

Hello everyone. When I checked the error Log I got this error:

Next Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '[email protected]' for key 'email' (SQL: insert into hr_employees

How do I resolve it?

Activity icon

Replied to Fields Are Not Being Updated In Cron Jobs

@silencebringer - I didn't say everything work. I said that I confirmed using employee_type_code. By the way, employee_type_code is in the list of fillable fields.

Kindly assist

Thank

Jul
27
1 week ago
Activity icon

Started a new Conversation Fields Are Not Being Updated In Cron Jobs

I am using Laravel-5.8 and Guzzle to get external using cron jobs to update the fields or create new ones in the local database.

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use Exception;
use Notification;
use GuzzleHttp\Client; 
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;

class UpdateCreateEmployee extends Command
{

   protected $signature = 'updatecreateemployees';
   protected $description = 'Update or Create Employee Profile';

   public function __construct()
   {
       parent::__construct();
   }

   public function handle()
   { 
    
    $client = new Client();
    $res = $client->request('GET','https://api.myapi.net/laravelapp/myemployees', [
       'query' => ['key' => 'jkklmssetyyy']
   ])->getBody();
    
    DB::beginTransaction();
   try { 
    
    $clientdatas = json_decode($res->getContents(), true);  

    
    foreach($clientdatas as $clientdata)
    {

        

        $payloads = [
            'username'                              => strtok($clientdata['email_company'], '@'),
            'first_name'                            => $clientdata['first_name'],
            'last_name'                             => $clientdata['last_name'],
            'other_name'                            => $clientdata['middle_name'],
            'employee_type_code'                    => $clientdata['resource_type'],
                      ]; 
        
        if(!isset($clientdata['staff_id'])) { 
           $payloads['nav_dept_id'] = $clientdata['department_id'];
        }     
        
        $employee = HrEmployee::updateOrCreate([
                    'employee_code' => $clientdata['staff_id'],
                    'email'         => $clientdata['email'],
                ], $payloads);       
        
        $user = User::updateOrCreate([
            'employee_code'                         => $employee->employee_code,
            'email'                                 => $employee->email,

        ],
        [
            'username'                              => $employee->username,
            'password'                              => bcrypt("123456"),
            'first_name'                            => $employee->first_name,
            'last_name'                             => $employee->last_name,
      
        ]);
                    
        if (! $user->hasRole('Employee')) {
            $user->assignRole('Employee');  
        }            
         
         $employee->update(['user_id' => $user->id]);
  
    }
    
       DB::commit();           
        } catch (Exception $exception) {
           Log::error($exception);
            DB::rollback();

        }              
    } 
}

From the external api, some of the employees have their resource_type updated.

But when I ran the cron job, the resource_type is not updated in the database.

How do I rsolve this?

Thanks

Jul
24
1 week ago
Activity icon

Replied to How To Perform Advance Format Using Maatwebsite Export

@marianomoreyra - I got this error:

Use of undefined constant current_terms

Use of undefined constant identities

From my code as shown above, I returned and mapped only $published_goals which I used for A4:E4.

How do I do likewise for $current_terms and $identities ?

Thanks

Activity icon

Replied to Advanced Format Of Laravel Excel Maatwebsites For Export

@marianomoreyra - When I added it this way:

    // Set cell A1 with Your Title
    $event->sheet->getDelegate()->setCellValue('A1', 'Your Title Here');

    // Set cells A2:B2 with current date
    $event->sheet->getDelegate()->setCellValue('A2', 'Report Date:');
    $event->sheet->getDelegate()->setCellValue('B2', now());

    $cellRange = 'B5:K5'; // All headers
    $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
    $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->getColor()
                ->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
    $event->sheet->getDelegate()->getStyle($cellRange)->getFill()
                ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
                ->getStartColor()->setARGB('FF17a2b8');
    $event->sheet->setAutoFilter($cellRange);

The initial formatting for:

    $cellRange = 'B5:K5'; // All headers

Did not take effect again

Activity icon

Started a new Conversation ERROR: Method Maatwebsite\Excel\Sheet::setOrientation Does Not Exist

I am using Laravel-5.8 and Maatwebsite-3.1 to export to excel.

While trying to format, I did page setup to orientation

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Events\BeforeWriting;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\FromView;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithMapping;
use \Maatwebsite\Excel\Sheet;
use Maatwebsite\Excel\Concerns\RegistersEventListeners;
use Illuminate\Support\Facades\DB;

class HrEmployeeGoalExport implements FromCollection, ShouldAutoSize, WithHeadings, WithEvents, WithMapping
{
public function registerEvents(): array
{
    return [
        AfterSheet::class    => function(AfterSheet $event) {

            $cellRange = 'A1:L1'; // All headers
            $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setName('Calibri')->setSize(14)->setBold($cellRange);
            $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->getColor()
                        ->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
            $event->sheet->getDelegate()->getStyle($cellRange)->getFill()
                        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
                        ->getStartColor()->setARGB('FF17a2b8');
            $event->sheet->setAutoFilter($cellRange);
            $event->sheet->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);                      
        },
    ];
 }    
}

When I tried to download, I got this error:

production.ERROR: Method Maatwebsite\Excel\Sheet::setOrientation does not exist. {"userId":469,"exception":"[object] (BadMethodCallException(code: 0): Method Maatwebsite\Excel\Sheet::setOrientation does not exist. at C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Support\Traits\Macroable.php:104) [stacktrace] #0 C:\xampp\htdocs\myapp\vendor\maatwebsite\excel\src\DelegatedMacroable.php(29): Maatwebsite\Excel\Sheet->__call('setOrientation', Array)

And when I used:

$event->sheet->getDelegate()->getPageSetup()->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);

I got this error:

production.ERROR: Class 'App\Exports\PageSetup' not found

How do I get this resolved?

Thanks

Activity icon

Replied to How To Perform Advance Format Using Maatwebsite Export

Please somebody help me with this

Activity icon

Replied to Advanced Format Of Laravel Excel Maatwebsites For Export

@marianomoreyra This one did not work

        // Set cell A1 with Your Title
        $event->sheet->setCellValue('A1', 'Your Title Here');

        // Set cells A2:B2 with current date
        $event->sheet->setCellValue('A2', 'Report Date:');
        $event->sheet->setCellValue('B2', now());

But only this worked

        $cellRange = 'B5:K5'; // All headers
        $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
        $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->getColor()
                    ->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
        $event->sheet->getDelegate()->getStyle($cellRange)->getFill()
                    ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
                    ->getStartColor()->setARGB('FF17a2b8');
        $event->sheet->setAutoFilter($cellRange);
Activity icon

Started a new Conversation How To Perform Advance Format Using Maatwebsite Export

I am trying to export my report to excel in my Laravel 5.8 project using Maatwebsites:

In Laravel-5.8, I am trying to export to Excel using Maatwebsite:

<?php

namespace App\Exports;

use App\User;
use Auth;

class StudentExport implements FromCollection, ShouldAutoSize, WithHeadings, WithMappings
{

    private $headings = [
        'Student ID', 
        'Name',
        'Class',
        'Status',
        'Teacher'
    ];

    public function collection()
    {
        $userCompany = Auth::user()->company_id;
        $userEmployee = Auth::user()->employee_id;
        $userId = Auth::user()->id;
        $employeecode = Auth::user()->employee_code;

        $current_terms = DB::table('appraisal_identity')->select('term_name')->where('company_id', $userCompany)->where('is_current', 1)->first()->term_name;
        $identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->pluck('id');
        $publishedgoals = AppraisalGoal::select('employee_code')->where('is_published', 1)->where('appraisal_identity_id', $identities)->where('company_id', $userCompany)->groupBy('employee_code')->get();  


        $published_goals = DB::table('hr_students AS e')
                    ->join('hr_employees AS em','em.id','=','e.teacher_id')
                     ->select(
                        'e.student_id',
                        DB::raw('CONCAT(e.first_name, " ", e.last_name) AS full_name'),
                        'e.student_class,
                        DB::raw('(CASE WHEN e.is_status = 3 THEN "Excellent" WHEN e.is_status = 2 THEN "Good" WHEN e.is_status = 1 THEN "Average" ELSE "Pass" END) AS student_status') 
                        DB::raw('CONCAT(em.first_name, " ", em.last_name) AS teacher_name')
                        
                 )
                    ->whereIn('e.student_id', $publishedgoals)
                ->distinct()
                ->get();

            $published_goals = $published_goals->unique('student_id');
       
           return collect($published_goals);
    } 

public function map($published_goals): array
{
    return [
       $published_goals->student_id,
       $published_goals->full_name,
       $published_goals->student_class,
       $published_goals->student_status,
       $published_goals->teacher_name,
   ];
 }  


public function headings() : array
{

    return $this->headings;
}    

public function registerEvents() : array
{
    return [
        AfterSheet::class    => function(AfterSheet $event) {
            $cellRange = 'A4:E4'; // All headers
            $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
            $event->sheet->getDelegate()->getStyle($cellRange)->getFont()->getColor()
                   ->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_WHITE);
            $event->sheet->getDelegate()->getStyle($cellRange)->getFill()
                   ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
                   ->getStartColor()->setARGB('FF17a2b8');
            $event->sheet->setAutoFilter($cellRange);
        },
    ];
  }   

}

I have written the code above to get this resuld:

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

However I want to:

However I want to:

  1. Merge A1:E1 and align center as STUDENT TERMINATION REPORT

  2. I want to make D2 to have the output of these variables together: $current_terms - $identities (For example, if $current_terms = 1st Term and $identities = 20. Then It will be 1st Term - 20 )

  3. I want to display the current date and time as A2:B2 (Report Date & Time: 20 July 2020 10:00 p.m.)

  4. A4:E4 as the Heading (A4->Student ID, B4->Name, C4->Class, D4->Status, E4->Teacher

The result should be as shown below:

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

How do I modify the code and formatting to achieve this?

Thank you

Jul
23
1 week ago
Activity icon

Awarded Best Reply on View Blade Search Filter And Pagination Disappears

Resolved. I added this:

<script>
$(document).ready(function() {
    $('#myTable').DataTable({
        stateSave: true,
    });
});
</script>


<table id="myTable">
Activity icon

Replied to View Blade Search Filter And Pagination Disappears

Resolved. I added this:

<script>
$(document).ready(function() {
    $('#myTable').DataTable({
        stateSave: true,
    });
});
</script>


<table id="myTable">
Activity icon

Replied to WhereIn Clause Not Giving Expected Result

@chr15k - Thanks so much. I don't know why I forgot that. Resolved

Activity icon

Started a new Conversation WhereIn Clause Not Giving Expected Result

I am trying to get the list of employees that belongs to the departments that a particular employee is the HR Service Office for that department. A particular employee can be the HR Service officer for more than one department. And a department have employees.

$employeecode = Auth::user()->employee_code;

// this gives the list of id of departments where the logged in user is the HR Service Officer. I did dd() and there are results.

$hrbpDepartments  = HrDepartment::select('id')->where('hr_business_partner_id', $employeecode)->get();

// this gives the list of employees (employee_code) that belong to the logged in user (HR Service). It is having results when I dd() id.

$hrbpEmployees = HrEmployee::select('employee_code')->whereIn('department_id', $hrbpDepartments)->get(); 

//this should gives the list of employees (employee_code) that did appraisal and the HR Service is the logged in users.

$publishedgoals = AppraisalGoal::select('employee_code')->whereIn('employee_code', $hrbpEmployees)->whereNull('deleted_at')->groupBy('employee_code')->get(); 

This gives no result. But there are employees. So, when I take one of the employee_code and added it this way I got result:

whereIn('employee_code', ['KK123'])

as in

$publishedgoals = AppraisalGoal::select('employee_code')->whereIn('employee_code', ['KK123'])->whereNull('deleted_at')->groupBy('employee_code')->get(); 

I got result.

How do I resolve this?

Thanks

Activity icon

Started a new Conversation View Blade Search Filter And Pagination Disappears

In my Laravel-5.8 application, when i used DB raw and Query Builder, the pagination and search filters in the view blade datatable disappears.

Controller

    $datas = DB::table('hr_employees AS e')
                ->leftJoin('appraisal_goals AS a', function($join) use ($identities)
                    {
                        $join->on('a.employee_id', '=', 'e.id')
                        ->where('a.appraisal_identity_id', '=', $identities)
                        ->whereNull('deleted_at');
                    })
                ->join('hr_departments AS d', function($join) use ($userCompany)
                    {
                        $join->on('e.department_id', '=', 'd.id')
                        ->where('d.company_id', '=', $userCompany);;
                    })                        
                ->join('hr_work_locations AS l', function($join) use ($userCompany)
                    {
                        $join->on('l.id', '=', 'e.work_location_id')
                        ->where('l.company_id', '=', $userCompany);;
                    })  
                ->leftJoin('hr_employees AS em', function($join) use ($userCompany)
                    {
                        $join->on('em.employee_code', '=', 'e.line_manager_id')
                        ->where('em.company_id', '=', $userCompany)
                        ->where('em.hr_status', '=', '0')
                        ->where('em.validation_status', '=', 'VALID')
                        ->whereNotIn('em.employee_type_code', [4, 5]);
                    }) 
                     ->where('e.company_id', '=', $userCompany)
                ->where('e.hr_status', '=', '0')
                ->where('e.validation_status', '=', 'VALID')
                ->whereNotIn('e.employee_type_code', [4, 5])
                ->select(
                        'e.employee_code',
                        DB::raw('CONCAT(e.first_name, " ", e.last_name) AS fullname'),
                        'e.email',
                        'd.dept_name',
                        'l.location_name',
                        'e.grade_level_name',
                        DB::raw('CONCAT(em.first_name, " ", em.last_name) AS manager'),
                        'em.email AS manager_email'                           )
                ->distinct()
                ->get(); 

    return view('employee_goal_reports')
                  ->with('datas', $datas);                       

view

            <tbody>
                @foreach($datas as $key => $data)
                    <tr data-entry-id="{{ $data->id }}">
                        <td>

                        </td>
                        <td>
                            {{ $data->employee_code ?? '' }}
                        </td>
                        <td>
                            {{ $data->fullname ?? '' }}
                        </td>

                    </tr>
                @endforeach
            </tbody> 


<script>
    $(function () {
  let deleteButtonTrans = '{{ trans('global.datatables.delete') }}'
  let deleteButton = {
    text: deleteButtonTrans,
    url: "{{ route('admin.products.massDestroy') }}",
    className: 'btn-danger',
    action: function (e, dt, node, config) {
      var ids = $.map(dt.rows({ selected: true }).nodes(), function (entry) {
          return $(entry).data('entry-id')
      });

      if (ids.length === 0) {
        alert('{{ trans('global.datatables.zero_selected') }}')

        return
      }

      if (confirm('{{ trans('global.areYouSure') }}')) {
        $.ajax({
          headers: {'x-csrf-token': _token},
          method: 'POST',
          url: config.url,
          data: { ids: ids, _method: 'DELETE' }})
          .done(function () { location.reload() })
      }
    }
  }
  let dtButtons = $.extend(true, [], $.fn.dataTable.defaults.buttons)
@can('product_delete')
  dtButtons.push(deleteButton)
@endcan

  $('.datatable:not(.ajaxTable)').DataTable({ buttons: dtButtons })
})

</script>

I just discovered that the general search filter and pagination are not showing

But when I have something like this, it appears:

public function index()
{
        $worklocations = HrWorkLocation::where('company_id', $userCompany)->get();
    
    return view('hr.work_locations.index')->with('worklocations', $worklocations);
}

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

How do I resolve this?

Thanks

Jul
22
2 weeks ago
Activity icon

Started a new Conversation How To Get Manager's Manager

I have three tables in mysql database: hr_employees, appraisal_goals and hr_departments

SELECT DISTINCT e.employee_code, concat(e.first_name,' ',e.last_name) Fullname, e.email,
CASE
    WHEN a.line_manager_mid_year_approved = 0 THEN "DRAFT"
    WHEN a.line_manager_mid_year_approved = 1 THEN "AWAITING APPROVAL"
    WHEN a.line_manager_mid_year_approved = 2 THEN "NOT APPROVED"
    WHEN a.line_manager_mid_year_approved = 3 THEN "APPROVED"
ELSE "NOT STARTED"
END AS line_manager_mid_year_approved,d.dept_name, concat(em.first_name,' ',em.last_name) as manager
   FROM hr_employees e
LEFT JOIN appraisal_goals a ON a.employee_id = e.id
INNER JOIN hr_departments d
ON e.department_id = d.id
LEFT JOIN hr_employees em
ON (em.employee_code = e.line_manager_id)
    WHERE e.company_id = 1 
AND e.hr_status = 0 
AND e.validation_status = 'VALID'
AND e.employee_type_code NOT IN (4,5);

Each employee have his own manager

I have been able to get employee's manager using:

concat(em.first_name,' ',em.last_name) as manager

and

LEFT JOIN hr_employees em ON (em.employee_code = e.line_manager_id)

Each manager will also have his own manager.

How do I now get manager's manager (manager of manager)

Thanks

Activity icon

Started a new Conversation How To Get Department Head In Query

I have three tables in mysql database: hr_employees, appraisal_goals and hr_departments

hr_departments have these fields:

	'id',
           'dept_name',
            'dept_head'


SELECT DISTINCT e.employee_code, concat(e.first_name,' ',e.last_name) Fullname, e.email,
CASE
    WHEN a.line_manager_mid_year_approved = 0 THEN "DRAFT"
    WHEN a.line_manager_mid_year_approved = 1 THEN "AWAITING APPROVAL"
    WHEN a.line_manager_mid_year_approved = 2 THEN "NOT APPROVED"
    WHEN a.line_manager_mid_year_approved = 3 THEN "APPROVED"
ELSE "NOT STARTED"
END AS line_manager_mid_year_approved,d.dept_name
   FROM hr_employees e
LEFT JOIN appraisal_goals a ON a.employee_id = e.id
INNER JOIN hr_departments d
ON e.department_id = d.id
    WHERE e.company_id = 1 
AND e.hr_status = 0 
AND e.validation_status = 'VALID'
AND e.employee_type_code NOT IN (4,5);

I can get department head (employee first_name and last_name) when hr_departments.dept_head = hr_employees.employee_code

How do I complete this query to get department head?

Thanks

Activity icon

Replied to Self Referencing Make Left Join Not To Give Correct Result

@jlrdw - I want the data I need to be in one query so that I can just render it in the blade blade from the controller

Activity icon

Replied to Self Referencing Make Left Join Not To Give Correct Result

@jlrdw - I applied the same thing, but I don't know why the self join is not making the left join to give the right result

Activity icon

Started a new Conversation Self Referencing Make Left Join Not To Give Correct Result

I have three tables in mysql database: hr_employees, appraisal_goals and hr_departments

SELECT DISTINCT e.employee_code, concat(e.first_name,' ',e.last_name) Fullname, e.email,
CASE
    WHEN a.line_manager_mid_year_approved = 0 THEN "DRAFT"
    WHEN a.line_manager_mid_year_approved = 1 THEN "AWAITING APPROVAL"
    WHEN a.line_manager_mid_year_approved = 2 THEN "NOT APPROVED"
    WHEN a.line_manager_mid_year_approved = 3 THEN "APPROVED"
ELSE "NOT STARTED"
END AS line_manager_mid_year_approved,d.dept_name,
e.grade_level_name, concat(em.first_name,' ',em.last_name) as manager
FROM hr_employees e
LEFT JOIN appraisal_goals a ON a.employee_id = e.id
INNER JOIN hr_departments d
ON e.department_id = d.id
INNER JOIN hr_employees em
ON em.employee_code = e.line_manager_id
WHERE e.company_id = 1 
AND e.hr_status = 0 
AND e.validation_status = 'VALID'
AND e.employee_type_code NOT IN (4,5);
  1. using left join, All the employees are to be selected whether they have data in hr_departments and appraisal_goals or not.

  2. Each employee have a line manager

Initially, without the self referencing (where no line manager data selected) everything was working perfectly. In order to get the manager full name, I did self referencing where em.employee_code = e.line_manager_id. As soon as I did this, the query only select the employees that have data in the appraisal_goals.

How do I correct this, so that the left join will still be working?

Thanks

Activity icon

Replied to How To Write MYSQL Left Join Query As Laravel Query

@jlrdw - I want to write it as RAW DB Query or Eloquent Query

Activity icon

Started a new Conversation How To Write MYSQL Left Join Query As Laravel Query

I have this MYSQL Query that is working fine

SELECT e.id, e.employee_code, concat(e.first_name,' ',e.last_name) Fullname, e.email, e.department_id, 
CASE
    WHEN a.line_manager_mid_year_approved = 0 THEN "DRAFT"
    WHEN a.line_manager_mid_year_approved = 1 THEN "AWAITING APPROVAL"
    WHEN a.line_manager_mid_year_approved = 2 THEN "NOT APPROVED"
    WHEN a.line_manager_mid_year_approved = 3 THEN "APPROVED"
ELSE "NOT STARTED"
END AS line_manager_mid_year_approved,
e.grade_level_name, e.work_location_id, e.line_manager_id
FROM hr_employees e
LEFT JOIN 
(SELECT * FROM appraisal_goals GROUP BY employee_id) a
ON a.employee_id = e.id
WHERE e.company_id = 1
AND a.is_active = 1
AND e.hr_status = 0 
AND e.validation_status = 'VALID'
AND e.employee_type_code NOT IN (4,5)
ORDER BY e.employee_code;

How do I write it as Laravel Query?

Thanks

Activity icon

Started a new Conversation How To Combine Laravel Left Join And Group By For Another Table

I am using Laravel and have two tables user and result.

      user                                    result
---------------------------          -------------------------------------
| `id`  | `name` |`active`|          | `id` |`user_id` |`status`|`identity`|
--------------------------            ------------------------------------
|   1   | Apia   | 1    |            |   1   |    1   |    2   |    1   |
|   2   | Tang   | 1    |            |   2   |    1   |    2   |    1   |
|   3   | Jemrom | 1    |            |   3   |    2   |    1   |    1   |
|   4   | Akwet  | 1    |            |   4   |    5   |    3   |    1   |
|   5   | Lamte  | 1    |            -------------------------------------
---------------------------

So the result should look like:

------------------------------
| `name` |`active` |`status`  |
------------------------------
| Apia   |    1    |`passed`  |
| Tang   |    1    |`passed`  |
| Akwet  |    1    |`awaiting`|
| Lamte  |    1    |`failed`  |
| Jerome  |    1    |`unavailable`  |
------------------------------

NB: For status in result table (1=awaiting, 2=passed,3=failed)

I want to select everything from user table using left join where active = 1 (ordered by names) and match with related user_id in result table where identity =1. The result table must be grouped by user_id. Where a user does not have data in result, it should display unavailable for status instead of null

How do I write this query in Laravel?

Thanks

Jul
21
2 weeks ago
Activity icon

Started a new Conversation Laravel Office 365 Mail Configuration

I have laravel-5.8 application.

Does any have the idea on how to configure my Laravel application to use office 365 for send email?

Thanks

Activity icon

Started a new Conversation How To Add Where Not Null Condition To Cron Job

In my Laravel-5.8, I have a cron job running.

public function handle()
{
    $client = new Client();
    $res = $client->request('GET','https://api.laravel.com/my-workers', [
       'query' => ['key' => 'kkdfhfn7755222']
   ])->getBody();

    $clientdatas = json_decode($res->getContents(), true);  
    
    foreach($clientdatas as $clientdata)
    {        
     
        $testing = HrTesting::updateOrCreate([
            'testing_name' => $clientdata['testing_location']
        ],
        [
                 'company_id'   => 1,          
        ]); 
    }

   }

I found that where $clientdata['testing_location'] is null, it still updates it in the table. How do I put it that where null, it should not perform any action?

Thanks

Jul
20
2 weeks ago
Activity icon

Replied to How To Map Nationality With Country In Laravel

@martinbean - If I import, how do I now make the nationality field to be on the same row with its already exisiting corresponding country_name

Activity icon

Started a new Conversation How To Map Nationality With Country In Laravel

In my Laravel-5.8, I am using MYSQL as the database and I have this model:

protected $table = 'config_countries';
protected $primaryKey = 'id';

protected $fillable = [
              'country_name',
              'country_code',
          ];

Already the table config_countries consist of data for all the countries.

However, I have this excel that consists of countries and nationalities:

nationality

I have already created a field in config_countries called nationality as varchar(100)

Without having to create another table, how do I map the nationalities with country and insert all the nationality beside the country?

Thank you.