noblemfd

Member Since 1 Year Ago

Experience Points
35,120
Total
Experience

4,880 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
9
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.

  • Community Pillar

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

Level 8
35,120 XP
Feb
26
2 days ago
Activity icon

Replied to Query Not Giving Expected Result In Laravel

@tovisbratsburg - How do I convert to mysql because of those parameters

Activity icon

Started a new Conversation Query Not Giving Expected Result In Laravel

In my Laravel-5.8, I have this Query:

$identities = DB::table('appraisal_identity')->select('id')->where('is_current', 1)->pluck('id');
$userCompany = Auth::user()->company_id;

    $my_query = 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)
                        ->where('a.is_visible', '=', 1)
                        ->where('a.is_special_project', '=', 0)                                    
                        ->whereNull('a.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);
                    })  
                ->join('hr_employee_types AS et', function($join) use ($userCompany)
                    {
                        $join->on('et.id', '=', 'e.employee_type_id')
                        ->where('et.company_id', '=', $userCompany)
		    ->where('et.include_appraisal', '=', 1);
                    })                         
                ->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');
                    }) 
                ->leftJoin('hr_employees AS emm', function($join) use ($userCompany)
                    {
                        $join->on('emm.employee_code', '=', 'em.line_manager_id')
                        ->where('emm.company_id', '=', $userCompany)
                        ->where('emm.hr_status', '=', '0');
                    })                        
                ->leftJoin('hr_employees AS eh', function($join) use ($userCompany)
                    {
                        $join->on('eh.employee_code', '=', 'd.hr_business_partner_id')
                        ->where('eh.company_id', '=', $userCompany)
                        ->where('eh.hr_status', '=', '0');
                    })    
                	->where('e.company_id', '=', $userCompany)
                	->where('e.hr_status', '=', '0')
		->whereIn('e.employee_code', [2, 3])
                ->select(
                        'e.employee_code',
                        DB::raw('CONCAT(e.first_name, " ", e.last_name) AS fullname'),
                        'e.email',
		    DB::raw('(CASE WHEN a.is_approved = 0 THEN "DRAFT" WHEN a.is_approved = 1 THEN "AWAITING APPROVAL" WHEN a.is_approved = 2 THEN "NOT APPROVED" WHEN a.is_approved = 3 THEN "APPROVED" ELSE "NOT STARTED" END) AS is_approved'),
                        DB::raw('(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'),
                        DB::raw('(CASE WHEN a.line_manager_year_end_approved = 0 THEN "DRAFT" WHEN a.line_manager_year_end_approved = 1 THEN "AWAITING APPROVAL" WHEN a.line_manager_year_end_approved = 2 THEN "NOT APPROVED" WHEN a.line_manager_year_end_approved = 3 THEN "APPROVED" ELSE "NOT STARTED" END) AS line_manager_year_end_approved'),
                        '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',
                        DB::raw('CONCAT(emm.first_name, " ", emm.last_name) AS manager_manager'),
                        DB::raw('CONCAT(eh.first_name, " ", eh.last_name) AS hrbp')
                       )
                ->distinct()
                ->get(); 

From the query above, I want to display all the employees, either the record matches or not. Then, compare the matching records.

The problem now is that whenever there is no matching record for work_location_id for any employee as in:

->join('hr_work_locations AS l', function($join) use ($userCompany)
   {
     $join->on('l.id', '=', 'e.work_location_id')
     ->where('l.company_id', '=', $userCompany);
   }) 

it won't add the employee detail into the list of the result. But I want all the employees either there is matching record or not.

How do I do it that whenever there is no matching record for work_location_id, it should just display "Not Specified" for work location instead of omitting the employee record?

Thanks.

Feb
23
5 days ago
Activity icon

Replied to How To Run Cron Jobs For Multiple Companies

@snapey - Thanks for your politeness. So sorry I didn't make it clear enough. What I mean is that without stating stating that company_id is 1 or 2 or 3,, like this, where('company_id', 1). How do I Assign Line Manager Roles to the user based on their company?

Thanks

Activity icon

Started a new Conversation How To Run Cron Jobs For Multiple Companies

I have this code in Laravel-5.8 cron jobs:

public function handle()
{
    $linemanager = User::distinct()->where('company_id', 1)->whereNotNull('line_manager_id')->pluck('line_manager_id');
    $users = User::whereIn('employee_code', $linemanager)->where('company_id', 1)->get();
    foreach ($users as $user) {
        if (! $user->hasRole('Line Manager')) {
           $user->assignRole('Line Manager');  
        }
    }        
 } 

Initially I have just one company. Each user table have company_id, that's why company_id is 1. I use the user table to Assign Line manager role (Spatie RBAC). I did this in the cron jobs. I have multiple companies with user table still having company_id.

How do I now re-write the cron jobs (Since I have multiple companies now and can't determine which is 1 and so on) to assign Line Manager roles to the users?

Thanks

Feb
18
1 week ago
Activity icon

Replied to How To Load Default Value On Some Input Fields When Form Loads

@michaloravec - Yes, I do. I thought it's possible to use javascript to do that. Thanks

Activity icon

Started a new Conversation How To Load Default Value On Some Input Fields When Form Loads

In my Laravel-5.8 project, I have this code in the view blade

<form action="{{route('identities.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
  {{csrf_field()}}
  <div class="col-sm-12">
    <div class="form-group">
      <label class="control-label text-right col-md-0"> Name<span style="color:red;">*</span></label>
      <input type="text" name="name" placeholder="Enter name here" class="form-control" value="{{old('name')}}">
    </div>
  </div>
  <div id="minRespondent" class="col-12 col-sm-6">
    <div class="form-group">
      <label class="control-label"> Min. Respondent:</label>
      <input id="minRespondent" type="number" name="min_respondent" placeholder="Example: 1,2,3, ..." class="form-control" value="{{old('min_respondent')}}" min="0" max="30">
    </div>
  </div>
  <div id="maxRespondent" class="col-12 col-sm-6">
    <div class="form-group">
      <label class="control-label"> Max. Respondent:</label>
      <input id="maxRespondent" type="number" name="max_respondent" placeholder="Example: 1,2,3, ..." class="form-control" value="{{old('max_respondent')}}" min="0" max="30">
    </div>
  </div>
  <button type="submit" id="submit_create" class="btn btn-primary">Save</button>
</form>

Each time the form loads, by default, I want:

id="minRespondent" to be 5

and

id="maxRespondent" to be 7

How do I achieve this?

Thanks

Feb
17
1 week ago
Activity icon

Started a new Conversation How To Add Condition To The Roles Retrieved By Logged User

I am using Spatie RBAC in my Laravel-5.8 application

I have this code in my user controller and view:

UserController

public function create()
{
    $roles = Role::get()->pluck('name', 'name');
    return view('admin.users.create', compact('roles','companies'));
}

view

    <div class="form-group {{ $errors->has('roles') ? 'has-error' : '' }}">
        <label for="roles">{{ trans('global.user.fields.roles') }}*
            <span class="btn btn-info btn-xs select-all">Select all</span>
            <span class="btn btn-info btn-xs deselect-all">Deselect all</span></label>
        <select name="roles[]" id="roles" class="form-control select2" multiple="multiple">
            @foreach($roles as $id => $roles)
                <option value="{{ $id }}" {{ (in_array($id, old('roles', [])) || isset($user) && $user->roles->contains($id)) ? 'selected' : '' }}>
                    {{ $roles }}
                </option>
            @endforeach
        </select>
        @if($errors->has('roles'))
            <p class="help-block">
                {{ $errors->first('roles') }}
            </p>
            @endif
    </div>

If the Role of the logged in user is not "Super Admin", the role select dropdown should retrieve other roles except "Super Admin". But if the logged in user is "Super Admin", it should retrieve all the roles including "Super Admin".

How do I achieve this?

Thanks

Activity icon

Started a new Conversation How To Delete Record Based On Condition

In my Laravel-5.8, I have these three (3) models:

class Parameter extends Model
{    
    protected $table = 'parameters';
    protected $primaryKey = 'id';
    protected $fillable = [
                  'max_score',
                  'min_score',
                  'identity_id',
              ];

    public function identity()
    {
        return $this->belongsTo('App\Models\Identity','identity_id');
    }
}


class Identity extends Model
{
    protected $table = 'identity';

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

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

    public function parameter()
    {
       return $this->hasOne(Parameter::class, 'identity_id');
    }    
}


class Goal extends Model
{
    protected $table = 'goals';

    protected $fillable = [
                  'id',
                  'identity_id',
                  'title',
              ]; 

    public function identity()
    {
        return $this->belongsTo('App\Models\Identity','identity_id');
    }        
}

From the model, Identity has a foreign key (identity_id) in Parameter, also Identity has foreign key (identity_id) in Goal.

I have this controller in Identity:

public function destroy($id)
{
    try 
    {          
        $identity = Identity::findOrFail($id);
        $identity->delete();
        Session::flash('success', 'Record deleted successfully.');
        return redirect()->back();
    } 
    catch (Exception $exception) {
            Session::flash('error', 'Record delete failed!.');
            return redirect()->back();
    }       
}   

I want the user to delete Identity Record based on these conditions:

  1. As the user tries to delete Identity, the application should check Parameter table and also delete the record where identity_id foreign key exist.

  2. Secondly, if record with identity_id exists in Goal table, the application should prevent the delete.

How do I adjust

public function destroy($id) 

to achieve these?

Thanks

Feb
15
1 week ago
Activity icon

Started a new Conversation Validate Required Based On Condition

I have this request rule in my Laravel-5.8 code:

public function rules()
{
    return [
        'activate_msf' => [
            'nullable',
                Rule::unique('appraisal_parameters')->where(function ($query) {
                return $query->where('company_id', $this->company_id)
                        ->where('activate_msf', $this->activate_msf);
                })
        ],        
        'max_internal_respondent' => [
            'nullable',
            'numeric',
            'min:1',
            'max:30',
            'gt:min_internal_respondent',
        ],             
        'min_internal_respondent' => [
            'nullable',
            'numeric',
            'min:1',
            'max:30',
        ],   
    ];
}

activate_msf is tinyint(1) which could either be 0 or 1.

How do I validate min_internal_respondent and max_internal_respondent to be required only when activate_msf = 1?

Thanks

Activity icon

Awarded Best Reply on How To Display Min And Max Based On Another Toggle

I've eventually resolved it using:

    <script type="text/javascript">   
        $("#activateMsf").bootstrapSwitch();
        $(document).ready(function(){
            $('#activateMsf').on('switchChange.bootstrapSwitch', function (e, data) {
                 var state=$(this).bootstrapSwitch('state');//returns true or false
                 if(state){
                    $("#minRespondent").show();
                    $("#maxRespondent").show(); 
                 }
                 else{
                    $("#minRespondent").hide();
                    $("#maxRespondent").hide();
                 }
             });
        });
    </script>
Activity icon

Replied to How To Display Min And Max Based On Another Toggle

I've eventually resolved it using:

    <script type="text/javascript">   
        $("#activateMsf").bootstrapSwitch();
        $(document).ready(function(){
            $('#activateMsf').on('switchChange.bootstrapSwitch', function (e, data) {
                 var state=$(this).bootstrapSwitch('state');//returns true or false
                 if(state){
                    $("#minRespondent").show();
                    $("#maxRespondent").show(); 
                 }
                 else{
                    $("#minRespondent").hide();
                    $("#maxRespondent").hide();
                 }
             });
        });
    </script>
Activity icon

Started a new Conversation How To Display Min And Max Based On Another Toggle

In my Laravel-5.8, I have this code:

StoreController

   $parameter = Parameter::create([
       'activate_msf'                      => $request->has('activate_msf'),
       'max_internal_respondent'           => $request->max_internal_respondent, 
       'min_internal_respondent'           => $request->min_internal_respondent,
    ]);

View blade:

           <div class="col-12 col-sm-2">
            <div class="form-group">
                <label class="control-label"> Activate MSF?:</label><br>
              <input type="checkbox" name="activate_msf"  class="form-control" unchecked data-bootstrap-switch data-off-color="danger" data-on-color="success" data-off-text="NO" data-on-text="YES">
            </div>
          </div>

           <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Min. Internal Respondent:<span style="color:red;">*</span></label>
              <input type="number" name="min_internal_respondent" placeholder="Example: 1,2,3, ..." class="form-control" value="{{old('min_internal_respondent')}}" min="1" max="30">  
            </div>
          </div>       
           <div class="col-12 col-sm-6">
            <div class="form-group">
              <label class="control-label"> Max. Internal Respondent:<span style="color:red;">*</span></label>
              <input type="number" name="max_internal_respondent" placeholder="Example: 1,2,3, ..." class="form-control" value="{{old('max_internal_respondent')}}" min="1" max="30">  
            </div>
          </div> 

What I want to achieve is that, if activate_mid_year = 0 then min_internal_respondent and max_internal_respondent should be hidden

But If activate_mid_year = 1, then min_internal_respondent and max_internal_respondent should be visible

How do I achieve this?

Feb
12
2 weeks ago
Activity icon

Replied to Production.ERROR: InvalidArgumentException: Data Missing In Laravel

@nakov - What do i do if the date is running null? The user did not select date of birth because it is not required.

Activity icon

Started a new Conversation Production.ERROR: InvalidArgumentException: Data Missing In Laravel

I am working on a project in Laravel-5.8. I have this in my model:

Model:

protected $fillable = [
              'id',
              'email',
              'hire_date',
              'first_name',
              'other_name',
              'last_name',
              'date_of_birth',
          ];

protected $dates = [
    'date_of_birth',
    'hire_date',
];

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

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

Then this is my controller.

Controller:

$arr = [
   'first_name'                => $request->first_name,
   'last_name'                 => $request->last_name,
   'hire_date'                 => $request->hire_date,
   'date_of_birth'             => $request->date_of_birth,
   'other_name'                => $request->other_name,
];

 $employee = HrEmployee::create($arr);

I use JQuery datepicker:

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

  }); <
/script>
<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="{{ old(" date_of_birth} ") }}" class="form-control birthDate">
    </div>
  </div>
  <!-- /.form-group -->
</div>

When I submitted the form, I got this error:

[2021-02-12 12:50:07] production.ERROR: InvalidArgumentException: Data missing in /var/www/html/peopleedgeapp/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php:623
Stack trace:
#0 /var/www/html/myapp/vendor/nesbot/carbon/src/Carbon/Traits/Creator.php(645): Carbon\Carbon::rawCreateFromFormat('d-m-Y', NULL, NULL)
#1 /var/www/html/myapp/app/Models/Hr/HrEmployee.php(156): Carbon\Carbon::createFromFormat('d-m-Y', NULL)
#2 /var/www/html/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(615): App\Models\Hr\HrEmployee->setDateOfBirthAttribute(NULL)
#3 /var/www/html/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php(569): Illuminate\Database\Eloquent\Model->setMutatedAttributeValue('date_of_birth', NULL)
#4 /var/www/html/myapp/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php(329): Illuminate\Database\Eloquent\Model->setAttribute('date_of_birth', NULL)

How do I get this resolved?

Thanks

Feb
11
2 weeks ago
Activity icon

Replied to How To Pass JSON Value From Dropdown As Route Parameter

No @michaloravec - Let me explain. Since I couldn't get the parameter then, I decide to pass it as a JSON get Request. I some of my projects, I have used JSON requests. But I'm finding it difficult to pass what I have as JSON into the route parameter. That's all

Activity icon

Started a new Conversation How To Pass JSON Value From Dropdown As Route Parameter

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

public function findIdentity(Request $request)
{
    $userCompany = Auth::user()->company_id;
    $identity = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('id',$request->id)->first();
    return response()->json([
        'identity' => $identity->id
    ]);        
}  

View blade:

< script type = "text/javascript" >
  $(document).ready(function() {
    $(document).on('change', '#identity', function() {
      var air_id = $(this).val();
      var op = "";
      $.ajax({
        type: 'get',
        url: '{{ route('
        get.identities.all ') }}',
        data: {
          'id': air_id
        },
        dataType: 'json', //return data will be json


        success: function(data) {
          console.log(data.identity);
          $('#identity_id').val(data.identity);

        },
        error: function() {

        }
      });
    });
  }); <
/script>
<div class="row" style="margin-bottom: 10px">
  <label class="control-label"> Performance Period:<span style="color:red;">*</span></label>
  <div class="col-sm-8">
    <select id="identity" name="identity_id" class="form-control">
      <option value="">--- Select Performance Period ---</option>
      @foreach ($identities as $ids => $name)
      <option value="{{ $ids }}" {{ request( 'identity_id')==$ids ? 'selected' : ''}}>{{ $name }}</option>
      @endforeach
    </select>
  </div>
  <input type="hidden" id="identity_id" class="form-control">
  <div class="col-xs-4">
    <button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>
    <form action="{{ route('performance_dashboard', $id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
      {{csrf_field()}}
      <button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
    </form>
  </div>
</div>

route:

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

From all the codes above, I am trying to get the id of the dropdown (select option) in the view blade into the route parameter.

How do I pass #identity_id as the parameter #id in:

{{ route('performance_dashboard', $id) }}
Feb
10
2 weeks ago
Activity icon

Replied to Production.ERROR: Undefined Variable: Id Laravel Blade

@michaloravec - How do I pass the id of the dropdown @foreach ($identities as $ids => $name) as the parameter

Activity icon

Replied to Laravel Dompdf Got Everything Overlapping

@yibr - Which one is css framework?

Activity icon

Started a new Conversation Production.ERROR: Undefined Variable: Id Laravel Blade

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

public function appraisal(Request $request)
{
try {        
        $userCompany = Auth::user()->company_id;
        $userId = Auth::user()->id; 
        $company = OrgCompany::where('id', $userCompany)->first();              
        $identities = Identity::where('company_id', $userCompany)->pluck('appraisal_name','id');
        $goals = AppraisalGoal::where('employee_id', $userId)->where(function ($query) {
                    $query->where('is_approved', 3)->orWhere('is_visible', 0);
                })->whereNull('deleted_at')->orderBy('goal_type_id');             

        $method = $request->method();

        if ($request->isMethod('post'))
        {
            $id = $request->input('identity_id');
            if ($request->has('search'))
            {
                // select search
                if($request->input('identity_id')){
                   $goals->where('identity_id',$request->input('identity_id'));
                }          
                $goals= $goals->get();  
                return view('appraisal-default',['goals' => $goals, 'identities' => $identities]);
            }
            elseif ($request->has('viewIdentity'))
            {
                // select goal identity
                if($request->input('identity_id')){
                   return view('performance_dashboard', $id);
                }          
            }
        }
        else
        {
            //select current year
            $goals= $goals->get();               
            return view('appraisal-default',['goals' => $goals, 'identities' => $identities]);
        }
    } catch (Exception $exception) {
        Log::error($exception);
        Session::flash('error', 'Action failed! Please try again');
        return back();
        }
}  

view blade: appraisal-default

<div class="row" style="margin-bottom: 10px">
  <label class="control-label"> Performance Period:<span style="color:red;">*</span></label>
  <div class="col-sm-8">
    <select id="identity" name="identity_id" class="form-control">
      <option value="">--- Select Performance Period ---</option>
      @foreach ($identities as $ids => $name)
      <option value="{{ $ids }}" {{ request( 'identity_id')==$ids ? 'selected' : ''}}>{{ $name }}</option>
      @endforeach
    </select>
  </div>

  <div class="col-xs-4">
    <button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>
    <form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
      {{csrf_field()}}
      <button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
    </form>
  </div>
</div>

In the view, I have two buttons with names: search and viewIdentity

When the

<select id="identity" name="identity_id" class="form-control"> 

is selected.

If search button is submitted, it displays the result on the same page. This is working.

However, where I'm having problem is when viewIdentity button is submitted. At this point it suppose to take the id of the dropdown as the parameter in:

<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
  {{csrf_field()}}
  <button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
</form>

and display the result in another page: performance_dashboard

I got this error in the view:

production.ERROR: Undefined variable: id

It points to this line in the view:

<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">

How do I get it resolved?

Thanks

Activity icon

Started a new Conversation Laravel Dompdf Got Everything Overlapping

I am using Laravel-5.8 barryvdh/laravel-dompdf to export to pdf:

I am using AdminLTE-3

controller:

$pdf = PDF::loadView('default-pdf',['goals' => $goals, 'company' => $company, 'employee' => $employee])->setPaper('a4', 'landscape');
                return $pdf->download('PDF-report.pdf');

view

@extends('layouts.pdf-main')

@section('content')
    <div class="row">
        <div class="col-lg-6 col-md-6 col-sm-12 col-xs-12">
            <h1>Testing</h1>

        </div>

    </div>

@endsection

I just observe everything in the page was overlapping even when I changed to bootstrap-4.

This only happens with dompdf

How do I resolve this?

Thanks

Feb
08
2 weeks ago
Activity icon

Replied to Production.ERROR: View [hr.grade_levels.index] Not Found

@michaloravec - Thanks. I don't know what really happened because the blade was there before

Activity icon

Started a new Conversation Production.ERROR: View [hr.grade_levels.index] Not Found

In my laravel-5.8 I have this code:

public function index()
{
        $grades = HrGradeLevel::all();
    return view('hr.grade_levels.index')->with('grades', $grades);
}

route:

Route::group(['prefix' => 'hr', 'as' => 'hr.', 'namespace' => 'Hr', 'middleware' => ['auth']], function () {

   Route::resource('grade_levels', 'HrGradeLevelsController');
});

I got this error:

production.ERROR: View [hr.grade_levels.index] not found

But it is there in the route list.

How do I resolve this?

Feb
07
3 weeks ago
Activity icon

Started a new Conversation Laravel Azure Socialite Authentication

In my Laravel-5.8 I am using Azure Socialite Authentication. I have this Login controller:

class LoginController extends Controller
{
    use AuthenticatesUsers;
    protected $redirectTo = '/dashboard';

    protected $username = 'username';
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function redirectToProvider()
    {
        return Socialite::with('azure')->redirect();
    }

    public function handleProviderCallback()
    {
         $azureUser = Socialite::with('azure')->user();
        try 
        {
            $user = User::where('email', $azureUser->email)->orWhere('username', $azureUser->user['mailNickname'])->first();
            if($user)
            {
                if(Auth::loginUsingId($user->id))
                {
                    $user->update([
                         'last_login_at' => now(),
                    ]);
                   return redirect()->intended('/dashboard');
                }
            }
        } 
        catch(\Exception $e) 
        {
            session()->flash("error", "Authentication failed, kindly contact the Administrator!");
            return redirect(route('login'));
        }
    }   
}

I observe that the catch(\Exception $e) is not being implemented

I want to attach these three conditions:

  1. If user details not in both DB and Azure, it should display a message: LOGIN NOT SUCCESSFUL or INCORRECT LOGIN DETAILS

  2. If user details not in DB, but in Azure: it should show the user a blank dashboard with the name you have in Azure. And a clear message stating that they need to contact the company HR to profile them in order for them to access more modules

  3. If user details are in DB but not in Azure, it should display a message: LOGIN NOT SUCCESSFUL or INCORRECT LOGIN DETAILS

How do I achieve these?

Thanks

Feb
05
3 weeks ago
Activity icon

Started a new Conversation How To Display Feedback Message When Data Is Null

I have this controller in Laravel-5.8:

public function index()
{
    $identities = DB::table('appraisal_identity')->select('id')->where('is_current', 1)->first();  
     
    $currentstatus = Goal::select('is_approved')->where('identity_id', $identities->id)->first();
    $goalsettingstatus = Parameter::select('activate_goal_setting')>first();

    $goals = Goal::where('identity_id', $identities->id)->where('is_visible', 1)->where('is_special_project', 0)->whereNull('deleted_at')->get();
 
    return view('student.goals.index')->with(['goals' => $goals])
            ->with('currentstatus', $currentstatus)
            ->with('goalsettingstatus', $goalsettingstatus);
}

It happens that there is no data for $identities. It is null, and this makes it to throw error at this line $currentstatus

How do I make Laravel to display feedback message that data is not available instead of the error page?

Thanks

Activity icon

Started a new Conversation ErrorException: Trying To Get Property 'max_score' Of Non-object

In my Laravel-5.8 application, I have this code:

Controller

$data = AppraisalGoalType::create([
   'name'                      => $request->name,
   'parent_id'                 => $request->parent_id,
   'max_score'                 => $request->max_score,
   'company_id'                => Auth::user()->company_id,
    ]);
   $data1 = DB::table('appraisal_goal_types')->select('max_score')->where('id', $request->parent_id)->whereNull('parent_id')->first();
   if(!empty($request->max_score)){
   $data->update(['max_score1' => $data1->max_score]);
  }else
  {
       $data->update(['max_score1' => 0]); 
  }

View

<div class="form-group">
    <label class="control-label"> Max. Score:</label>
    <input type="number" name="max_score" class="form-control" value="{{old('max_score')}}" step="0.01" placeholder="Enter maximum weight here: 15, 50, 75 etc" style="width: 100%;">
</div>

When I tried to insert into the database, I got this error:

ErrorException: Trying to get property 'max_score' of non-object

I dd($data); and got:

  #original: array:12 [▼
    "name" => "dxxddxdx"
    "parent_id" => null
    "max_score" => "56"
    "company_id" => 

and dd($data1); gives null which is true. I already have a conditional statement

I see that it has "max_score" => "56"

Why the error and how do I resolve it?

Thanks

Activity icon

Replied to Laravel Query With Multiple Where Clause

@michaloravec - I got Syntax error unexpected: }

})->first();

Activity icon

Started a new Conversation Laravel Query With Multiple Where Clause

In my Laravel-5.8, I have this query:

$companies = $this->getCompanies();
$company_credentials = OrgSocialiteSetting::where('id', $companies->id)->first();

$azureUser = Socialite::with('azure')->user();

$user = User::where('company_id', $company_credentials->company_id)->where('email', $azureUser->email)->orWhere('username', $azureUser->user['mailNickname'])->first();

I have two where and one orWhere

I want to tie where('email', $azureUser->email)->orWhere('username', $azureUser->user['mailNickname']) together.

How do I achieve that?

Thanks

Feb
04
3 weeks ago
Activity icon

Started a new Conversation Config File Returns NULL In Laravel

In my Laravel Laravel-5.8, I created a config file:

<?php

  return [
      'default_domain_name' => 'myapp',
  ];

inside myconfig.php as in: app/config/myconfig.php

But when I did var_dump(config('myconfig')) I got NULL

How do I register and reference app/config/myconfig.php or is there something else I need to do?

Activity icon

Started a new Conversation How To Register Middleware In Kernel

I have created this middleware which I want to use for domain and subdomains (myapp.com, comany1.myapp.com) routing in multi-company application:

namespace App\Http\Middleware;

use App\Models\Organization\OrgCompany;
use Closure;

class VerifyAppDomain
{
    public function handle($request, Closure $next)
    {
        $request->get('domain_name', $this->getBaseDomain());

        $company = OrgCompany::where('subdomain', $subdomain)->firstOrFail();

        $request->session()->put('subdomain', $company);

        return $next($request);
    }

    protected function getBaseDomain()
    {
        return config('myconfig.default_domain_name', 'myapp');
    }
}

route/web.php

Route::domain('myapp')
->group([
    'middleware' => ['veryfy_app_domain'] // Add your VerifyAppDomain Middleware here
    ], function () {

    Route::group(['prefix' => '/' . $defaultDomain], function () {
        Route::get('/', function ($id) {
           //
        });     
    });

I have all these in kernel:

protected $middlewareGroups = [
    'web' => [
 
    ],
];

protected $routeMiddleware = [

];

protected $middlewarePriority = [

];
Activity icon

Started a new Conversation AADSTS700016: Application With Identifier 'my_id' Was Not Found In The Directory 'company2.com'

I have two companies with microsoft account:

company1.com company2.com

I am using azure AD as socialite login in my Laravel-5.8 application.

I have registered company1.com in microsoft:

'azure' => [
    'client_id' => env('AZURE_KEY','9999'),
    'client_secret' => env('AZURE_SECRET','iii'),
    'redirect' => env('AZURE_REDIRECT_URI','https://myapp/login/azure/callback')
],

I decided to use the same azure account for company2.com since they are both microsoft account but got this error:

AADSTS700016: Application with identifier 'my_id' was not found in the directory 'company2.com'

How do I resolve this?

Thanks

Feb
03
3 weeks ago
Activity icon

Started a new Conversation InvalidArgumentException: The Separation Symbol Could Not Be Found

I'm trying to import in Laravel-5.8 using Maatwebsites-3.1

public function model(array $row)
{                  
    $employee_data = [

      'date_of_birth'                     => $this->transformDate($row['date_of_birth']),

    ];        
    
   $employee = HrEmployee::create($employee_data);
}

public function transformDate($value, $format = 'Y-m-d')
{
    try {
        return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
    } catch (\ErrorException $e) {
        return \Carbon\Carbon::createFromFormat($format, $value);
    }
}

My date format in Excel is YYYY-MM-DD

Model:

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

Then I got this error:

[2021-02-03 20:39:23] production.ERROR: InvalidArgumentException: The separation symbol could not be found
Trailing data in C:\xampp\htdocs\peopleedge\vendor\nesbot\carbon\src\Carbon\Traits\Creator.php:623

Stack trace: #0 C:\xampp\htdocs\myapp\vendor\nesbot\carbon\src\Carbon\Traits\Creator.php(645): Carbon\Carbon::rawCreateFromFormat('d-m-Y', '1985-04-10', NULL) #1 C:\xampp\htdocs\myapp\app\Models\Hr\HrEmployee.php(156): Carbon\Carbon::createFromFormat('d-m-Y', '1985-04-10')

How do I resolve it?

Thanks

Activity icon

Started a new Conversation Advance Error Trapping In Laravel Maatwebsite Excel Upload

I tried to upload data from excel into database using Maatwebsite-3.1 in Laravel-5.8

public function import(Request $request){
    $request->validate([
        'file' => 'required|max:10000|mimes:xlsx,xls',
    ]);

  $path1 = $request->file('file')->store('temp'); 
  $path=storage_path('app').'/'.$path1;  

    try{

        Excel::import(new EmployeesImport, $path);        
        
    } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
        $failures = $e->failures();
        $all_errors = $e->errors();
        Log::error($failures);
        Log::error($all_errors);
        Log::error($e);
        $errormessage = "";
        
     foreach ($failures as $failure) {
         $errormess = "";
         foreach($failure->errors() as $error)
         {
             $errormess = $errormess.$error;
         }
         $errormessage = $errormessage." ,\n At Row ".$failure->row().", ".$errormess."<br>";
     }                  
     
         Session::flash('error', $errormessage); 
         return back();            
    }catch (\Illuminate\Database\QueryException $e)
    {
        $errorCode = $e->errorInfo[1];
        if($errorCode == 1062){
        Log::error($e);
        DB::rollback();
        Session::flash('error', 'You have a duplicate entry problem!');
        }
        return back();

    }
    
    Session::flash('success', 'Employee Records Imported Successfully');
    return redirect()->route('hr.employees.index');  
}

The file was not uploaded, yet it displays 'Employee Records Imported Successfully'

Non of these could log the error:

        $failures = $e->failures();
        $all_errors = $e->errors();
        Log::error($failures);
        Log::error($all_errors);
        Log::error($e);

Even when I used:

try {
   $import->import('import-users.xlsx');
} catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
   $failures = $e->failures();
 
    foreach ($failures as $failure) {
       $failure->row(); // row that went wrong
       $failure->attribute(); // either heading key (if using heading row concern) or column index
       $failure->errors(); // Actual error messages from Laravel validator
       $failure->values(); // The values of the row that has failed.
     }
}

How else do I log the error in Laravel Maatwebsite upload?

Thanks

Activity icon

Started a new Conversation Rules Requests Causing Issues In Laravel Maatwebsites Excel Upload

I am using Maatwebsites-3.1 in Laravel-5.8 for Excel upload. This is shown below:

use Maatwebsite\Excel\Concerns\WithMultipleSheets;

class EmployeesImport implements WithMultipleSheets
{
    public function sheets(): array
    {
        return [
            new FirstEmployeeSheetImport()
        ];
    }
}

The function above is used to call the one shown below:

class FirstEmployeeSheetImport implements ToModel, WithHeadingRow, WithBatchInserts, WithValidation
{
    protected $department, $employeetype, $designation, $worklocation, $nationality, $gradelevel;
    private $errors = []; // array to accumulate errors
    private $gendercode = ['Female' => 0, 'Male' => 1];
    private $hrstatus = ['Active' => 0, 'Inactive' => 1];
    private $maritalstatus = ['Single' => 1, 'Married' => 2, 'Separated' => 3, 'Divorced' => 4, 'Widow(er)' => 5, 'Other' => 6];
    use Importable;

    public function model(array $row)
    {           
        $this->worklocation = $row['work_location_id'];
        $this->nationality = $row['nationality_id'];
        $this->gradelevel = $row['grade_level_id'];

        $employee_data = [
            'employee_code'                     => $row['employee_code'],
            'first_name'                        => $row['first_name'],
            'other_name'                        => $row['other_name'] ?? '',
            'last_name'                         => $row['last_name'],
            'email'                             => $row['email'],
            'email2'                            => $row['email2'] ?? '',
            'line_manager_id'                   => $row['line_manager_id'] ?? '',
            'gender_code'                       => $this->gendercode[$row['gender_code']] ?? null,
            'hr_status'                         => $this->hrstatus[$row['hr_status']] ?? null,
            'company_id'                        => Auth::user()->company_id,
                  ];        

       $employee = HrEmployee::create($employee_data);

    }

    public function getWorkLocation(){
        if(!empty($this->worklocation) || !$this->worklocation){

            return HrWorkLocation::where('location_name',$this->worklocation)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
        } else {
            return 0;
        }
    }       

    public function getNationality(){
        return ConfigCountry::where('country_code2',$this->nationality)->where('company_id',Auth::user()->company_id)->pluck('employee_code')->first();
    }

    // this function returns all validation errors after import:
    public function getErrors()
    {
        return $this->errors;
    }

    public function rules(): array
    {
        return [
            'employee_code' => [
                'required',
                'string',
                'min:2',
                'max:20',               
                Rule::unique('hr_employees')->where(function ($query) {
                    return $query->where('company_id', Auth::user()->company_id);
                })                 
            ],  
            'first_name' => [
                'required',
                'string',
                'min:3',
                'max:50'               
            ], 
            'other_name' => [
                'nullable',
                'string',
                'max:50'               
            ], 
            'last_name' => [
                'required',
                'string',
                'min:3',
                'max:50'               
            ], 
            'email' => [
                'required',
                'email', // official email
                'max:100',  
                Rule::unique('hr_employees')->where(function ($query) {
                    return $query->where('company_id', Auth::user()->company_id);
                })                 
            ],
            'line_manager_id' => 'nullable',            
            'gender_code' => 'nullable',
            'department_id' => 'required',
            'employee_type_id' => 'required',
            'designation_id' => 'required',
            'hr_status' => 'required',
                      ];
    }  

    public function customValidationAttributes()
    {
        return [
            'employee_code'                     => 'Staff ID',
            'first_name'                        => 'First Name',
            'other_name'                        => 'Middle Name',
            'last_name'                         => 'Last Name',
            'email'                             => 'Official Email',
            'line_manager_id'                   => 'Line Manager',            
            'gender_code'                       => 'Gender',
            'department_id'                     => 'Department',
            'employee_type_id'                  => 'Employee Type',
            'designation_id'                    => 'Designation',
            'hr_status'                         => 'HR Status',
        ];
    }        

    public function validationMessages()
    {
        return [
        ];
    }

    public function transformDate($value, $format = 'Y-m-d')
    {
        try {
            return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
        } catch (\ErrorException $e) {
            return \Carbon\Carbon::createFromFormat($format, $value);
        }
    } 

    public function batchSize(): int
    {
        return 200;
    }    

    public function headingRow(): int
    {
        return 1;
    }            
}

Then I have this in the controller:

public function import(Request $request){
    $request->validate([
        'file' => 'required|max:10000|mimes:xlsx,xls',
    ]);

  $path1 = $request->file('file')->store('temp'); 
  $path=storage_path('app').'/'.$path1;  

    try{
        Excel::import(new EmployeesImport, $path);        
        
    } catch (\Maatwebsite\Excel\Validators\ValidationException $e) {
        $failures = $e->failures();
        $all_errors = $e->errors();
        Log::error($failures);
        Log::error($all_errors);
        Log::error($e);
        $errormessage = "";
        
     foreach ($failures as $failure) {
         $errormess = "";
         foreach($failure->errors() as $error)
         {
             $errormess = $errormess.$error;
         }
         $errormessage = $errormessage." ,\n At Row ".$failure->row().", ".$errormess."<br>";
     }                  
     
         // Session::flash('error', 'Excel file is not imported!');
         Session::flash('error', $errormessage); 
         return back();            
    }catch (\Illuminate\Database\QueryException $e)
    {
        $errorCode = $e->errorInfo[1];
        if($errorCode == 1062){
        Log::error($e);
        DB::rollback();
        Session::flash('error', 'You have a duplicate entry problem!');
        }
        return back();
    }       
    Session::flash('success', 'Employee Records Imported Successfully');
    return redirect()->route('hr.employees.index');       
} 

The problem is that, When I tried t upload the excel file it shows that it was successful. But I found that no data is store in the database.

I eventually found that it's not recognising:

  Rule::unique('hr_employees')->where(function ($query) {
      return $query->where('company_id', Auth::user()->company_id);
  })

and I'm using it to validate the uniqueness of each attribute with company_id

How do I resolve this issues?

Thank you

Activity icon

Replied to Azure Socialite Login In Multi-company Application With Single DB

@bobbybouwmann - I'm sorry to still ask this question. I don't have the domain in the session. What I'm saying is that I registered this:

   'azure' => [
    'client_id' => env('AZURE_KEY','gggg'),
    'client_secret' => env('AZURE_SECRET','fffff'),
    'redirect' => env('AZURE_REDIRECT_URI','https://myapp/login/azure/callback')
 ],	

with microsoft in my microsoft account in order to allow me laravel socialite login. Do I need to do the same thing for the other subdomains (https://company1.myapp and https://company2.myapp) I just created?

Activity icon

Replied to Azure Socialite Login In Multi-company Application With Single DB

@bobbybouwmann - I created this middleware for route:

use App\Models\Organization\OrgCompany;
use Closure;

    class VerifyDomain
    {
        public function handle($request, Closure $next)
        {
            $domain == "myapp"; // your company app name
            $path = $request->getPathInfo(); // should return /company1.myapp or /company2.myapp or /myapp 
            if (strpos($path, ".") !== false) { // if path has dot.
                list($subdomain, $main) = explode('.', $path);
                if(strcmp($domain, $main) !== 0){
                    abort(404); // if domain is not myapp then throw 404 page error
                }
            } else{
                if(strcmp($domain, $path) !== 0){
                    abort(404); // if domain is not myapp then throw 404 page error
                }
                $subdomain = ""; // considering for main domain value is empty string.
            }

            $company = OrgCompany::where('subdomain', $subdomain)->firstOrFail(); // if not found then will throw 404

            $request->session()->put('subdomain', $company); //store it in session

            return $next($request);
        }
    }	

How do I link this with the azure socialite?

Secondly, Do I still need to create this:

   'azure' => [
      'client_id' => env('AZURE_KEY','gggg'),
      'client_secret' => env('AZURE_SECRET','fffff'),
      'redirect' => env('AZURE_REDIRECT_URI','https://myapp/login/azure/callback')
  ],		

for each of the domain/subdomains?

Activity icon

Replied to Azure Socialite Login In Multi-company Application With Single DB

@bobbybouwmann - Do I still need to create this:

   'azure' => [
       'client_id' => env('AZURE_KEY','gggg'),
       'client_secret' => env('AZURE_SECRET','fffff'),
       'redirect' => env('AZURE_REDIRECT_URI','https://myapp/login/azure/callback')
   ],		

for each of the domain/subdomains?

Activity icon

Replied to Azure Socialite Login In Multi-company Application With Single DB

@bobbybouwmann - Kindly pardon me, I have these few questions:

Since this is the azure credential, I have in services for the main/initial domain:

   'azure' => [
       'client_id' => env('AZURE_KEY','gggg'),
       'client_secret' => env('AZURE_SECRET','fffff'),
       'redirect' => env('AZURE_REDIRECT_URI','https://myapp/login/azure/callback')
   ],	
  1. How will this affect the other sub-domain (https://company1.myapp.com, https://company2.myapp.com and so on)?

  2. If the subdomain field in companies table is null, then it is https://myapp.com. How will redirectToProvider() handle this?

  3. As you stated here "It's better to handle this in a middleware so it works automatically for other parts of your application as well.", how do I handle it in middleware?

Thanks

Activity icon

Started a new Conversation Azure Socialite Login In Multi-company Application With Single DB

In my Laravel-5.8 I am using Azure Socialite Login.

class LoginController extends Controller
{
    use AuthenticatesUsers;
    protected $redirectTo = '/dashboard';
    protected $username = 'username';

    public function redirectToProvider()
    {
        return Socialite::with('azure')->redirect();
    }

    public function handleProviderCallback()
    {
         $azureUser = Socialite::with('azure')->user();
        try 
        {
            $user = User::where('email', $azureUser->email)->orWhere('username', $azureUser->user['mailNickname'])->first();
            if($user)
            {
                if(Auth::loginUsingId($user->id))
                {
                    $user->update([
                         'last_login_at' => now(),
                    ]);
                   return redirect()->intended('/dashboard');
                }
            }
        } 
        catch(\Exception $e) 
        {
            session()->flash("error", "Authentication failed, kindly contact the Administrator!");
            return redirect(route('login'));
        }
    }   
}


'azure' => [
   'client_id' => env('AZURE_KEY','mykey'),
   'client_secret' => env('AZURE_SECRET','myazuresecret'),
   'redirect' => env('AZURE_REDIRECT_URI','https://myapp/login/azure/callback')
],

This is working and it uses: https://myapp.com

But I'm now asked to make it multi-company application using single DB. There is a company table and each table have company_id

Each having this url:

https://myapp.com   
https://company1.myapp.com
https://company2.myapp.com

I now have these tables:

class Company extends Model
{
  protected $table = 'companies';
  protected $fillable = [
            'id',
            'company_name',
            'subdomain',
        ];
}

From the company table, where subdomain is null then it is https://myapp.com , while subdomain field could be company1 or company2 and so on.

class User extends Authenticatable
{
   protected $fillable = [
    'name', 
    'email', 
    'company_id',
    'password', 
 ];
}

The question is on the azure url redirect:

'redirect' => env('AZURE_REDIRECT_URI','https://myapp/login/azure/callback')

since it is redirecting to the main domain myapp.

What effect will this have on company1.myapp.com and company2.myapp?

How do I make it redirect to the subdomains also?

Thanks

Feb
02
3 weeks ago
Activity icon

Replied to Unique Rule For Two Fields Failed In Laravel

In my route/web.php I have this:

Route::resource('departments', 'HrDepartmentsController'); 

Then when I did php artisan route:list I got

| POST               | hr/departments                               | hr.departments.store         | App\Http\Controllers\Hr\[email protected]          | web,auth           |
| GET|HEAD           | hr/departments/create                        | hr.departments.create        | App\Http\Controllers\Hr\[email protected]         | web,auth           |
| PUT|PATCH          | hr/departments/{department}                  | hr.departments.update        | App\Http\Controllers\Hr\HrDepartmentsController[email protected]         | web,auth           |
| GET|HEAD           | hr/departments/{department}/edit             | hr.departments.edit          | App\Http\Controllers\Hr\[email protected]           | web,auth           |
Activity icon

Replied to Unique Rule For Two Fields Failed In Laravel

@michaloravec - The edit generates this error:

[2021-02-02 14:15:17] production.ERROR: Trying to get property 'id' of non-object

Activity icon

Replied to Unique Rule For Two Fields Failed In Laravel

@michaloravec - How do I change the one for edit?

I have this:

        'dept_name' => [
            'required',
            'string',
            'min:2',
            'max:80',   
            Rule::unique('hr_departments', 'dept_name', 'company_id')->ignore($this->department)
        ],
Activity icon

Started a new Conversation Unique Rule For Two Fields Failed In Laravel

In my Laravel-5.8, I have this model:

class HrDepartment extends Model
{
    public $timestamps = false;
    protected $table = 'hr_departments';
    protected $fillable = [
                  'company_id',
                  'dept_name',
              ];

    public function company()
    {
        return $this->belongsTo('App\Models\Organization\OrgCompany', 'company_id');
    }
}

I tried to use Request Rules

class StoreDepartmentRequest extends FormRequest
{
    public function authorize()
    {
        return \Gate::allows('department_create');
    }

    public function rules()
    {
        return [
            'dept_name' => [
                'required',
                'string',
                'min:2',
                'max:80',               
                Rule::unique('hr_departments', 'dept_name', 'company_id')
            ],

        ];
    }
    public function messages()
    {
        return [
            'dept_name.max:80' => 'Department Name cannot be more than 80 characters.',
            'dept_name.unique' => 'Department Name already exists.',
            'dept_name.required' => 'Please enter the Department Name.',                       
        ];
    }
}

Controller

public function store(StoreDepartmentRequest $request)
{     
        $department = HrDepartment::create([
            'dept_name'         => $request->dept_name,
            'company_id'        => Auth::user()->company_id,
        ]);
        Session::flash('success', 'Department is created successfully');
        return redirect()->route('hr.departments.index');return redirect()->route('hr.departments.index');  
    }        
}

I entered dept_name, Services for company 1, when I entered Services for company 2, I got this error:

'Department Name already exists.',

Why and how do I resolve it?

Thanks

Activity icon

Started a new Conversation How To Link Domain And Sub-domain In Route With Azure Socialite Login

In my Laravel-5.8 application, I have a multi-company application using a single database without using package. Each table have a company_id derived from the company table as shown below:

id | company_name       |    subdomain
1  | Main               |
2  | Company1           |    company1
3  | Company2           |    company2

Main=>  localhost:8888/myapp
Company1=>localhost:8888/company1.myapp
Company2=>localhost:8888/company2.myapp

I have these models:

class Copmany extends Model
{
  protected $table = 'organizations';
  protected $fillable = [
     'id',
     'company_name',
     'subdomain',   
 ];
}

class User extends Authenticatable
{
    protected $fillable = [
        'name', 
        'username',
        'email', 
        'password', 
        'company_id', 
    ]; 

    public function company()
    {
        return $this->belongsTo('App\Models\Company');
    }
}

Also I am using Azure Socialite Login.

class LoginController extends Controller
{
    use AuthenticatesUsers;
    protected $redirectTo = '/dashboard';
    protected $username = 'username';

    public function redirectToProvider()
    {
        return Socialite::with('azure')->redirect();
    }

    public function handleProviderCallback()
    {
         $azureUser = Socialite::with('azure')->user();
        try 
        {
            $user = User::where('email', $azureUser->email)->orWhere('username', $azureUser->user['mailNickname'])->first();
            if($user)
            {
                if(Auth::loginUsingId($user->id))
                {
                    $user->update([
                         'last_login_at' => now(),
                    ]);
                   return redirect()->intended('/dashboard');
                }
            }
        } 
        catch(\Exception $e) 
        {
            session()->flash("error", "Authentication failed, kindly contact the Administrator!");
            return redirect(route('login'));
        }
    }   
}

I created a middleware:

class VerifyDomain
{
 public function handle($request, Closure $next)
 {
    $domain == "myapp"; // your company app name
    $path = $request->getPathInfo(); // should return /company1.myapp or /company2.myapp or /myapp 
    if (strpos($path, ".") !== false) { // if path has dot.
        list($subdomain, $main) = explode('.', $path);
        if(strcmp($domain, $main) !== 0){
            abort(404); // if domain is not myapp then throw 404 page error
        }
    } else{
        if(strcmp($domain, $path) !== 0){
            abort(404); // if domain is not myapp then throw 404 page error
        }
        $subdomain = ""; // considering for main domain value is empty string.
    }

    $company = Company::where('subdomain', $subdomain)->firstOrFail(); // if not found then will throw 404

    $request->session()->put('subdomain', $company); //store it in session

    return $next($request);
 }
}

Already, I have two (2) route groups in the route/web.php wgich looks like this:

Route::get('/', ['as' => '/', 'uses' => '[email protected]']);

Auth::routes();
Route::get('/dashboard', '[email protected]')->name('dashboard');

  // Config Module
  Route::group(['prefix' => 'config', 'as' => 'config.', 'namespace' => 'Config', 'middleware' => ['auth']], function () {
    Route::resource('countries', 'ConfigCountriesController');
    Route::resource('nationalities', 'ConfigNationalitiesController');
});

 // HR Module
  Route::group(['prefix' => 'hr', 'as' => 'hr.', 'namespace' => 'Hr', 'middleware' => ['auth']], function () { 
    Route::resource('designations', 'HrDesignationsController');
    Route::resource('departments', 'HrDepartmentsController');  
    Route::resource('employee_categories', 'HrEmployeeCategoriesController');

});

A user can exit in more that one organization.

When a user logins in with azure socialite, I want the application to check the domain and sub-domain route and use it to get the company_id, then map it with the company_id in the user tables.

For instance, if user logs in using localhost:8888/myapp, the application use it to get the company_id in the user table, and if it is localhost:8888/company1.myapp, it does likewise and so on.

The user should only see the profile based on his company. Also should only see it's company data.

How do I achieve this from the route and LoginController?

Jan
30
4 weeks ago
Activity icon

Started a new Conversation How To Set Condition In Maatwebsite Laravel/Excel Upload

I am using Laravel-5.8 and Maatwebsite-3.1 for Excel upload into database in my Application.

I have this code:

class FirstLeaveSheetImport implements ToModel, WithHeadingRow, WithBatchInserts, WithValidation
{
    protected $staffid;
    private $errors = []; 

    use Importable;

    public function model(array $row)
    {   
        $this->staffid = $row['staff_id'];

        return new HrLeaveRequest([
            'employee_id'                       => $this->getStaffId(),
            'leave_type'                        => $row['leave_type'], 
            'commencement_date'                 => $this->transformDate($row['commencement_date']),
            'resumption_date'                   => $this->transformDate($row['resumption_date']),
            'company_id'                        => Auth::user()->company_id,
            'gender'                      	    => $row['gender'], 
        ]);        

    }

    public function getStaffId(){
        if(!empty($this->staffid)){
            return HrEmployee::where('employee_code',$this->staffid)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
        } else {
            return 0;
        }
    }   

    public function getErrors()
    {
        return $this->errors;
    } 

    public function transformDate($value, $format = 'Y-m-d')
    {
        try {
            return \Carbon\Carbon::instance(\PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($value));
        } catch (\ErrorException $e) {
            return \Carbon\Carbon::createFromFormat($format, $value);
        }
    }  

    public function headingRow(): int
    {
        return 1;
    }       
}

I want to apply condition to two columns from the excel sheet.

If leave_type = 'Annual', it should insert 0 into the database, 'Maternity' =1, 'Paternity' = 2, and if nothing is in the excel, it should insert null.

Likewise for column gender, 'Female' = 0, 'Male' =1 and Empty cell = null.

How do I achieve this?

Thanks

Jan
29
4 weeks ago
Activity icon

Started a new Conversation How To Handle Domain And Sub-domain In Route Using Laravel MiddleWare

In my Laravel-5.8 application, I have a multi-company application using a single database. Each table have a company_id derived from the company table as shown below:

id | company_name       |    subdomain
1  | Main               |
2  | Company1           |    company1
3  | Company2           |    company2

Main=>  localhost:8888/myapp
Company1=>localhost:8888/company1.myapp
Company2=>localhost:8888/company2.myapp

I created a middleware:

class VerifyDomain
{
 public function handle($request, Closure $next)
 {
    $domain == "myapp"; // your company app name
    $path = $request->getPathInfo(); // should return /company1.myapp or /company2.myapp or /myapp 
    if (strpos($path, ".") !== false) { // if path has dot.
        list($subdomain, $main) = explode('.', $path);
        if(strcmp($domain, $main) !== 0){
            abort(404); // if domain is not myapp then throw 404 page error
        }
    } else{
        if(strcmp($domain, $path) !== 0){
            abort(404); // if domain is not myapp then throw 404 page error
        }
        $subdomain = ""; // considering for main domain value is empty string.
    }

    $company = Company::where('subdomain', $subdomain)->firstOrFail(); // if not found then will throw 404

    $request->session()->put('subdomain', $company); //store it in session

    return $next($request);
 }
}

Already, I have two (2) route groups in the route/web.php wgich looks like this:

Route::get('/', ['as' => '/', 'uses' => '[email protected]']);

Auth::routes();
Route::get('/dashboard', '[email protected]')->name('dashboard');

  // Config Module
  Route::group(['prefix' => 'config', 'as' => 'config.', 'namespace' => 'Config', 'middleware' => ['auth']], function () {
    Route::resource('countries', 'ConfigCountriesController');
    Route::resource('nationalities', 'ConfigNationalitiesController');
});

 // HR Module
  Route::group(['prefix' => 'hr', 'as' => 'hr.', 'namespace' => 'Hr', 'middleware' => ['auth']], function () { 
    Route::resource('designations', 'HrDesignationsController');
    Route::resource('departments', 'HrDepartmentsController');  
    Route::resource('employee_categories', 'HrEmployeeCategoriesController');

});

I have 2 issues:

  1. If subdomain field is null, then the route should be for main domain: Main=> localhost:8888/myapp else localhost:8888/company1.myapp or localhost:8888/company2.myapp

2.How do I accomodate the route groups above into this:

 Route::domain('localhost:8888/myapp')->group(function () {
   Route::get('/', function ($id) {
       //
    });
 });

Route::domain('localhost:8888/{subdomain}.myapp')->group(function () {
   Route::get('/', function ($company_name, $id) {
       $company = Company::where('subdomain', $subdomain)->firstOrFail();
       // send the value of $company to data to send different view data 
   });
});
Activity icon

Replied to How To Rectify Your Connection To This Site Is Not Secure

@martinbean - I'm so sorry for disturbing you.

I still get the same error.

Then when I did:

sudo certbot renew --nginx --dry-run

I got this this:

Congratulations, all renewals succeeded. The following certs have been renewed: /etc/letsencrypt/live/myapp.com/fullchain.pem (success) /etc/letsencrypt/live/company1.myapp.com/fullchain.pem (success) /etc/letsencrypt/live/company2.myapp.com/fullchain.pem (success) ** DRY RUN: simulating 'certbot renew' close to cert expiry ** (The test certificates above have not been saved.)

And yet still showing:

your connection to this site is not secure

Activity icon

Replied to How To Rectify Your Connection To This Site Is Not Secure

@martinbean - How to apply the certificate of the domain (myapp.com) for the sub-domains (company1.myapp.com, company2.myapp.com)

Thanks

Activity icon

Replied to How To Rectify Your Connection To This Site Is Not Secure

@tray2 - None of the sites is working anymore. domain and subdomains.

I have done this several times:

sudo certbot --nginx -d myapp.com -d www.myapp.com

Nothing seems to work

https://myapp.com

https://company1.myapp.com

https://company2.myapp.com

https://company3.myapp.com

I keep on having:

your connection to this site is not secure This site can’t be reached

Kindly assist