noblemfd

Member Since 1 Year Ago

Experience Points
37,430
Total
Experience

2,570 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
37,430 XP
May
27
2 weeks ago
Activity icon

Replied to How To Only Enable Add Button Based On Condition

@michaloravec - The solution I did was not consistent. I forgot to mention something. May be that's what's affection it. :

If the last record is previous year, it should automatically make the button visible. But for the current year, it should apply any of the conditions for the rules.

Activity icon

Replied to How To Only Enable Add Button Based On Condition

There is something I forgot to mention @silencebringer :

If the last record is previous year, it should automatically make the button visible. But for the current year, it should apply any of the conditions for the rules.

Activity icon

Started a new Conversation How To Only Enable Add Button Based On Condition

I have a Laravel-8 project with this model:

protected $fillable = [
              'id',
              'employee_id',
              'leave_status',
              'commencement_date',
              'resumption_date',
              'created_at'
          ];

protected $dates = [
    'commencement_date',
    'resumption_date',
    'created_at',
    'updated_at',
];

View:

<div class="panel-heading clearfix">
  <div class="container-fluid">
    @if ($currentstatus)

    <div style="margin-bottom: 10px;" class="row">
      <div class="col-lg-12">
        <a class="btn btn-info" href="{{ route(" service.leave_requests.create ") }}">
                        Add
                    </a>
      </div>
    </div>
    @endif

  </div>
</div>

I want the Add button to only be visible when:

1. leave_status is 0 for the last record (order by created_at)

or

2. leave_status is 4 and resumption_date is greater than or equal to today's date (order by created_at) for the last record.

or

3. leave_status is 3 (order by created_at) for the last record.

I tried the code below, but it's not working.

 $userID         = Auth::user()->id;

 $currentstatus = HrLeaveRequest::select('leave_status')->where('employee_id', $userID)->whereIn('leave_status', [0, 3, 4])->orderBy('created_at', 'DESC')->first();

How do I achieve this?

Thanks

May
21
3 weeks ago
Activity icon

Started a new Conversation How To Get Company_id Of The Logged In User From A Related Table

I am trying to get the logged in user's company_id, In my Laravel 8 Job Portal application. I have these models:

  • Department
  • User
  • Company
  • CompanyProfile

A User can only appear once on the users table with unique email. But he can have more than one CompanyProfile, since he can work remotely for more than one Company:

These are the models:

class Department extends Model
{
    protected $table = 'departments';

    protected $primaryKey = 'id';

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

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

class Company extends Model
{    
    protected $table = 'companies';

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

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

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


class User extends Authenticatable
{
    protected $hidden = [
        'password',
        'remember_token',
    ];
    
    protected $fillable = [
        'first_name',
        'other_name',
        'last_name',
        'username',
        'email', 
        'password', 
    ];

    public function profile(){
        return $this->hasMany('App\Models\CompanyProfile', 'employee_id');
    }

    public function company(){
        return $this->hasMany('App\Models\CompanyProfile', 'company_id');
    }
}

class CompanyProfile extends Model
{    
    protected $table = 'company_profiles';

    protected $primaryKey = 'id';

    protected $fillable = [
        'id',
        'user_id',
        'company_id',
        'department_id',
        'employment_date',
    ];
}

Having in mind that the company_id is not in the User model, How do I get the company_id of the Logged in User in the DepartmentController?

public function index()
{           
    $departments = Department::where('company_id', ...)->get();
    return view('departments.index')->with('departments', $departments);
}

Thanks

May
19
3 weeks ago
Activity icon

Replied to Column Not Found: 1054 Unknown Column 'ip_address'

So sorry @corvs . I used id_address instead of ip_address.

Thanks

Activity icon

Started a new Conversation Column Not Found: 1054 Unknown Column 'ip_address'

In Laravel-8 application, I am tring to use this function:

public static function addToLog($subject, $logType=null, $subjectHint=null)
{
	$log = [];
	$log['subject'] = $subject;
    $log['log_type'] = $logType;
    $log['subject_hint'] = $subjectHint;
	$log['log_url'] = Request::fullUrl();
	$log['log_method'] = Request::method();
	$log['ip_address'] = Request::ip();
	$log['agent'] = Request::header('user-agent');
	$log['user_id'] = auth()->check() ? auth()->user()->id : 1;
	LogActivityModel::create($log);
}

But I got this error:

[2021-05-19 13:25:55] local.ERROR: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ip_address' in 'field list' in C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:465

But ip_address column exists.

How do I get it resolve?

Thanks

Activity icon

Started a new Conversation How To Get The Company ID Of The Logged In User From A Related Table

In my Laravel-8 Job Portal application, I have these four (4) tables (models):

Department, User, Company and CompanyProfile

A user can only appear once on the user table with unique email. But he can have more than one company profile, since he can work remotely for more than one company:

These are the models:

class Department extends Model
{
    protected $table = 'departments';
    protected $primaryKey = 'id';
    protected $fillable = [
                'id',
                'company_id',
                'name',
            ];

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

class Company extends Model
{    
     protected $table = 'companies';
     protected $primaryKey = 'id';
     protected $fillable = [
                'id',
                'name',
                'org_image',
             ];

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

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

class User extends Authenticatable
{
    protected $hidden = [
        'password',
        'remember_token',
    ];
    
    protected $fillable = [
        'name', 
        'first_name',
        'other_name',
        'last_name',
        'username',
        'email', 
        'password', 
    ];

    public function profile(){
        return $this->hasMany('App\Models\CompanyProfile', 'employee_id');
    }

    public function company(){
        return $this->hasMany('App\Models\CompanyProfile', 'company_id');
    }
}

class CompanyProfile extends Model
{    
     protected $table = 'company_profiles';
     protected $primaryKey = 'id';
     protected $fillable = [
                'id',
                'user_id',
                'company_id',
                'department_id',
                'employment_date',
            ];
}

Having in mind that the company_id is not in the User Model, How to get the company_id of the Logged in user in the DepartmentController?

public function index()
{           
     $departments = Department::where('company_id', ...)->get();
     return view('departments.index')->with('departments', $departments);
}

Thanks

May
16
4 weeks ago
Activity icon

Replied to How To Create User Roles Based On Companies Using Laravel Spatie

@snapey - I have developed applications using that. But what I mean is this: The spatie role tables has these fields -

Roles --name --guard_name

I want to possible add another field company_id whereby each company create it's own roles. Not the general roles created. Thanks

Activity icon

Replied to How To Create User Roles Based On Companies Using Laravel Spatie

@snapey - What I mean is this: I want each company to create it's roles, and the roles created by each company will be assigned to the company users

Activity icon

Started a new Conversation How To Create User Roles Based On Companies Using Laravel Spatie

I am using Laravel-Spatie Permission and Laravel-8 for User Role-Based Access Level:

I have these tables:

User Model:

<?php

namespace App;

use App\Model;
use Carbon\Carbon;
use Hash;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;
    use SoftDeletes;

    protected $fillable = [
        'first_name',
        'other_name',
        'last_name',
        'company_id', 
        'updated_at',
        'created_at',
    ];

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

Company Model:

<?php

namespace App\Models\Organization;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Company extends Model
{
    public $timestamps = false;
    protected $table = 'companies';

    protected $primaryKey = 'id';

    protected $fillable = [
                'id',
                'company_name',
                'address1',
                'address2',
                'org_head',
                'created_by',
                'created_at',
                'updated_by',
                'updated_at',
                'is_active'
            ];
    public function users()
    {
        return $this->hasMany('App\User');
    }
 }

Each user is attached at least to a company. Apart from the SuperAdmin Role, I want Roles to belong to companies. That is, each company should create it's own Roles.

How do I achieve this?

May
14
4 weeks ago
Activity icon

Replied to How To Login With Either Email Or Phone Using Laravel Resful Api

@tykus - I was trying to use it to reference the Request Rules shown below. But I got stuck.

public function rules()
{
    return [
    'emailOrPhone' => 'required|string',
    'password' => 'required|string',
    'remember_me' => 'boolean'
    ];
}
Activity icon

Started a new Conversation How To Login With Either Email Or Phone Using Laravel Resful Api

In my Laravel-8 restful API application, I am using Laravel Passport.

I have this code in my request rules:

public function rules()
{
    return [
    'emailOrPhone' => 'required|string',
    'password' => 'required|string',
    'remember_me' => 'boolean'
    ];
}

Controller:

public function login(LoginRequest $request)
{
    try{
        $userCred = User::where('email', $request->emailOrPhone)
        ->orWhere('mobile_number', $request->emailOrPhone)
        ->first();
        $credentials = request(['email', 'password']);
        $credentials['active'] = 1;
        $credentials['deleted_at'] = null;
        if(!Auth::attempt($credentials))
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        $user = $request->user();
        $tokenResult = $user->createToken('iDriver');
        $token = $tokenResult->token;
        if ($request->remember_me)
            $token->expires_at = Carbon::now()->addWeeks(1);
        $token->save();
        return response()->json([
            'access_token' => $tokenResult->accessToken,
            'token_type' => 'Bearer',
            'expires_at' => Carbon::parse($tokenResult->token->expires_at)->toDateTimeString()
        ]);
    }catch(\Exception $e) {
        return $this->error($e->getMessage(), $e->getCode());
    }
}

How do I re-write the Controller code, so that users can Login with either email or mobile_number?

Thanks

Activity icon

Started a new Conversation Target [App\Interfaces\Auth\AuthInterface] Is Not Instantiable While Building

In my Laravel-8 application, I am trying to bind Repository to an Interface

I have this code:

App\Providers\RepositoryServiceProvider:

class RepositoryServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(
            'App\Interfaces\Auth\AuthInterface',
            'App\Repositories\Auth\AuthRepository'
        );
    }
}

config\app:

App\Providers\RepositoryServiceProvider::class,

Then the interface looks like this:

namespace App\Interfaces\Auth;

use Illuminate\Http\Request;
use App\Http\Requests;

interface AuthInterface
{
    public function register(Request $request);
}

    public function register(DriverRequest $request)
    {
        DB::beginTransaction();
        try {
            $newUser = User::create([
                'first_name' => $request->first_name,
                'last_name' => $request->last_name,
                'email' => preg_replace('/\s+/', '', strtolower($request->email)),
                'password' => bcrypt($request->password)
            ]);

            DB::commit();
            return $this->success('Signup Successfully Done, please check your email to activate account', $newUser);
        } catch(\Exception $e) {
            DB::rollback();
            Log::error($e);
            return $this->error($e->getMessage(), $e->getCode());
        }
    }
}

Controller

use App\Interfaces\Auth\AuthInterface;
class AuthController extends Controller
{
    protected $authInterface;

    public function __construct(AuthInterface $auth)
    {
        $this->authInterface = $auth;
    }

    public function register(Request $request)
    {
        return $this->authInterface->register($request);
    }
}

When I did php artisan route:list, I got this error:

Illuminate\Contracts\Container\BindingResolutionException

  Target [App\Interfaces\Auth\AuthInterface] is not instantiable while building [App\Http\Controllers\Api\V1\Auth\AuthController].

  at C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Container\Container.php:1049
1045▕         } else {
1046▕             $message = "Target [$concrete] is not instantiable.";
1047▕         }
1048▕
➜ 1049▕         throw new BindingResolutionException($message);
1050▕     }
1051▕
1052▕     /**
1053▕      * Throw an exception for an unresolvable primitive.

 1   C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Container\Container.php:842
  Illuminate\Container\Container::notInstantiable("App\Interfaces\Auth\AuthInterface")

  2   C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Container\Container.php:714
  Illuminate\Container\Container::build("App\Interfaces\Auth\AuthInterface")

How do I get it resolved?

Thanks

Activity icon

Started a new Conversation How To Create And Send Activation Token After Successful User Registration

I am using Laravel-8 api passport for a project. I have created the user registration as shown below:

public function register(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required|max:55',
        'email' => 'email|required|unique:users',
        'password' => 'required|confirmed'
    ]);

    $validatedData['password'] = bcrypt($request->password);

    $user = User::create($validatedData);

    $accessToken = $user->createToken('authToken')->accessToken;

    return response([ 'user' => $user, 'access_token' => $accessToken]);
}

How do I create and send activation token after successful user registration?

Thank you

May
10
1 month ago
Activity icon

Started a new Conversation How To Resolve WhereDate Function Issue

I have this code in Laravel-5.8

$currentDate = Carbon::now()->format('Y-m-d');

$currentstatus = HrLeaveRequest::select('leave_status')->whereDate('resumption_date, '<=', $currentDate)->whereIn('leave_status', [1, 3, 4])->orderBy('created_at', 'DESC')->first();

$currentDate = 2021-05-10 $resumption_date = 2021-05-12

But when I dd($currentstatus), I got null

How do I resolve this?

Thanks

May
05
1 month ago
Activity icon

Started a new Conversation Errno: 150 Foreign Key Constraint Is Incorrectly Formed In Migration

In my Laravel-8 application, I have this migration:

public function up()
{
    Schema::create('profiles', function (Blueprint $table) {
		$table->bigIncrements('id');
        $table->bigInteger('user_id');
		$table->string('first_name',50);
		$table->string('last_name',50);
        $table->string('other_name',50)->nullable();
		$table->string('gender',20);
        $table->string('user_photo',350)->nullable();
		$table->integer('nationality_id');
		$table->string('marital_status',50);
		$table->date('dob')->nullable();
		$table->string('address', 300)->nullable();
        $table->integer('country_id')->nullable();
        $table->integer('state_id')->nullable();
        $table->integer('city_id')->nullable();
		$table->string('cv_file',350)->nullable();
        $table->text('summary')->nullable();
		$table->timestamps();

        $table->foreign('user_id')->references('id')->on('users');
        $table->foreign('nationality_id')->references('id')->on('countries');
        $table->foreign('country_id')->references('id')->on('countries');
        $table->foreign('state_id')->references('id')->on('state_origins');
        $table->foreign('city_id')->references('id')->on('cities');
    });
}

When I did php artisan migrate, I got this error:

SQLSTATE[HY000]: General error: 1005 Can't create table hrm.profiles (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table profiles add constraint profiles_user_id_foreign foreign key (user_id) references users (id))

This is the users table:

    Schema::create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name', 100)->nullable();
        $table->string('email', 80)->nullable();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->string('avatar', 200)->nullable();
        $table->boolean('active')->default(false);
        $table->string('activation_token', 250)->nullable();
        $table->rememberToken();
        $table->timestamps();
        $table->softDeletes()->nullable();
        $table->timestamp('last_login_at')->nullable();
    });
}

How do I resolve this?

Thanks

May
01
1 month ago
Activity icon

Started a new Conversation Your Requirements Could Not Be Resolved To An Installable Set Of Packages Issue

I am using Windows Operation system to run php Laravel-8 Application. The PHP version for all the projects in my Windows Local System is PHP-Version3.8. All the Laravel Projects in my Local System has ("php": "^7.3|^8.0",)

However, I did a pull request from a Team Project but it is PHP-Version4. The Project also uses Laravel-8 Framework ("php": "^7.4|^8.0",)

When I tried to run composer install on the downloaded project, I got this error:

Your lock file does not contain a compatible set of packages. Please run composer update.

Problem 1
  - Root composer.json requires php ^7.4|^8.0 but your php version (7.3.8) does not satisfy that requirement.
  Problem 2
  - lcobucci/clock is locked to version 2.0.0 and an update of this package was not requested.
  - lcobucci/clock 2.0.0 requires php ^7.4 || ^8.0 -> your php version (7.3.8) does not satisfy that requirement.
Problem 3
  - lcobucci/jwt is locked to version 4.0.3 and an update of this package was not requested.
  - lcobucci/jwt 4.0.3 requires php ^7.4 || ^8.0 -> your php version (7.3.8) does not satisfy that requirement.
Problem 4
  - lcobucci/jwt 4.0.3 requires php ^7.4 || ^8.0 -> your php version (7.3.8) does not satisfy that requirement.
  - league/oauth2-server 8.2.4 requires lcobucci/jwt ^3.4 || ^4.0 -> satisfiable by lcobucci/jwt[4.0.3].
  - league/oauth2-server is locked to version 8.2.4 and an update of this package was not requested.

Then when I did composer update, the error is just this:

Your requirements could not be resolved to an installable set of packages.

Problem 1
 - Root composer.json requires php ^7.4|^8.0 but your php version (7.3.8) does not satisfy that requirement.

All the Projects are using composer-2

If I upgrade my Local system to PHPV-7.4, I will have issues with deployed projects.

How do I I get this resolved?

Thanks

Apr
27
1 month ago
Activity icon

Started a new Conversation Syntax Error Or Access Violation: 1067 Invalid Default Value For 'active' In Migration

In my Laravel-8 application, I have created users table using migration. How I want to add two new columns. I have this:

class AlterTableUsers extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('avatar', 200)->after('password')->nullable();
            $table->tinyInteger('active', 1)->after('avatar')->nullable()->default(0);
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn('avatar');
            $table->dropColumn('active');
        });
    }

When I did:

php artisan migrate

I got these errors:

SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'active' (SQL: alter table users add avatar varchar(200) null after password, add active tinyint null default '0' auto_increment primary key after avatar)

1 C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:465 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1067 Invalid default value for 'active'")

2 C:\xampp\htdocs\myapp\vendor\laravel\framework\src\Illuminate\Database\Connection.php:465 PDO::prepare("alter table users add avatar varchar(200) null after password, add active tinyint null default '0' auto_increment primary key after avatar")

How do I get it resolved?

Thanks

Apr
24
1 month ago
Activity icon

Started a new Conversation How To Add Walkthrough To Laravel Project

I have a project in Laravel-8. I want to add walkthrough that will guide users on the application as shown in the diagram.

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

I have never done it before. How do I achieve this?

Thanks.

Apr
18
1 month ago
Activity icon

Started a new Conversation How To Use Maatwebsite Excel Import In Laravel Restful API

Initially I have full Laravel Application. In it I use Maatwebsite-3.1 to import from Excel into the database as shown below:

class GradesImport implements
    ToCollection,
    WithHeadingRow,
    SkipsOnError,
    WithValidation,
    SkipsOnFailure
{
    use Importable, SkipsErrors, SkipsFailures;//, SkipsFailures, SkipsErrors; 

    public function collection(Collection $rows)
    {            
        foreach ($rows as $row) 
        {
            $this->gradelevel = $row['grade_level_code'];         
            HrEmployee::where('company_id', auth()->user()->company_id)
                ->where('employee_code', $row['staff_id'])
                ->where('email', $row['official_email'])     
                ->update([
                    'grade_level_id' => $this->getGradeLevel(),
                ]);
        }
    } 
    
    public function rules(): array
    {
        return [
            '*.employee_code' => [
                'required',
                'min:2',
                'max:20',               
            ], 
            '*first_name' => [
                'required',
                'string',
                'min:3',
                'max:50'               
            ],  
            '*last_name' => [
                'required',
                'string',
                'min:3',
                'max:50'               
            ],            
            '*grade_level_code'            => 'required',  
            '*official_email' => [
                'required',
                'email', // official email
                'max:100',               
            ],            
        ];    
    } 
    
    public function customValidationAttributes()
    {
        return [
            'company_id'                                => 'Company',
            'grade_level_code'                          => 'Grade Level Code',
            'employee_code'                             => 'Staff ID',
            'first_name'                                => 'First Name',
            'last_name'                                 => 'Last Name',            
        ];
    }
    
    public function getGradeLevel(){
        if(!empty($this->gradelevel) || !$this->gradelevel){

            return Grade::where('grade_level_code',$this->gradelevel)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
        } else {
            return 0;
        }
    }  
    
    public function headingRow(): int
    {
        return 1;
    }         
}

The above code is working fine in plain excel.

But Now I'm to convert it to Laravel Restful API and then use Angular-11 as the frontend.

How do I achieve this with the same code? Or is there any better way?

Thanks

Apr
05
2 months ago
Activity icon

Replied to Api Login Not Giving Expected Feedback Message

@snapey - I changed the first to Invalid.

return $this->sendError('Invalid.', ['error'=>'Invalid']);

So I got Invalid

Activity icon

Started a new Conversation Api Login Not Giving Expected Feedback Message

In my Project I am using Laravel-8, laravel-passport and spatie-permission for restful api. Already, I have this code in the Controller.

I have this controller

 public function adminLogin(Request $request)
 {
      if (auth('web')->attempt($request->only('email', 'password'))) {
         $user = Auth::guard('web')->user();
         if (!$user->hasRole('Super Admin')) {
              auth('web')->logout();
             return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
         }

         $success['token'] =  $user->createToken('MyApp')-> accessToken;
         $success['name'] =  $user->name;

         return $this->sendResponse($success, 'User login successfully.');
     }
     else{
         return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
     }
 }:

If the logged in user is not 'Super Admin' Role, it should return:

return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);

The logged in user is 'Super Admin', yet it returns the error.

'Super Admin' is part of the current user's role, yet I am getting this feedback:

{"success":false,"message":"Unauthorised.","data":{"error":"Unauthorised"}}

It has to do with this line:

   if (!$user->hasRole('Super Admin')) {
      auth('web')->logout();
     return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
   }

database dump

   CREATE TABLE `roles` (
     `id` bigint(20) UNSIGNED NOT NULL,
     `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
     `guard_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
     `created_at` timestamp NULL DEFAULT NULL,
     `updated_at` timestamp NULL DEFAULT NULL
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


   INSERT INTO `roles` (`id`, `name`, `guard_name`, `created_at`, `updated_at`) 
   VALUES
   (1, 'Super Admin', 'web', '2019-11-13 12:11:38', NULL),
   (2, 'Employee', 'web', '2019-11-13 12:11:38', NULL),
   (3, 'HOD', 'web', '2019-11-13 12:11:38', NULL);


   CREATE TABLE `model_has_roles` (
     `role_id` bigint(20) UNSIGNED NOT NULL,
     `model_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
     `model_id` bigint(20) UNSIGNED NOT NULL
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

   INSERT INTO `model_has_roles` (`role_id`, `model_type`, `model_id`) VALUES
   (1, 'App\Models\User', 1),
   (2, 'App\Models\User', 1);

What could be the problem and how do I get it resolved?

Thanks

Activity icon

Replied to How To Add Spatie Role Condition In Login

Eventually solved it using:

public function adminLogin(Request $request)

    if (Auth::attempt($request->only('email', 'password'))) {
        $user = Auth::user();

        if (!$user->hasRole('Super Admin') {
            Auth::logout();

            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        }

        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        $success['name'] =  $user->name;

        return $this->sendResponse($success, 'User login successfully.');
     }

    return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
   }
Activity icon

Started a new Conversation How To Add Spatie Role Condition In Login

I am using Laravel-8, laravel-passport and spatie-permission for restful api. Already, I have this code in the Controller.

I have this controller for the Admin:

public function adminLogin(Request $request)
{
    if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){
        $user = Auth::user();
        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        $success['name'] =  $user->name;

        return $this->sendResponse($success, 'User login successfully.');
    }
    else{
        return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
    }
}

I want only 'Super Admin' to be able to use the Admin Controller to Login. If not 'Super Admin', it should indicate unathorized.

How do I include the code below to what I already have above or any other best way?

    if($user->hasRole('Super Admin'))
        $res = User::with(['roles', 'employee', 'company'])->find($user->id);
    else
        $res = User::with('roles')->find($user->id);
Mar
31
2 months ago
Activity icon

Started a new Conversation Laravel Deployed Application Not Secured Using Certbot

I am using ubuntu-20.04 for Laravel-8 application. When I deployed to the server I ran this:

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

sudo certbot renew --dry-run

After showing success, I still got this on the browser:

Not Secure: Your connection is not private

The folder in sites-available is like this:

server {
    root /var/www/html/myapp;
    index index.html index.htm index.nginx-debian.html;
    server_name example.com;

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

    listen [::]:443 ssl ipv6only=on; # managed by Certbot
    listen 443 ssl; # managed by Certbot
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

}
server {
   if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot

    listen 80;
    listen [::]:80;
    server_name example.com;
    return 404; # managed by Certbot
}

How do I get this resolved?

Thanks

Mar
30
2 months ago
Activity icon

Replied to How To Convert Time In Seconds To Human Readable

@piljac1 - When I did:

{{ CarbonInterval::seconds($duration['time_spent'])->cascade()->forHumans()  ?? '' }}

I got the error:

[previous exception] [object] (Error(code: 0): Class 'CarbonInterval' not found

Activity icon

Started a new Conversation How To Convert Time In Seconds To Human Readable

In my Laravel-8, I have this in my view blade:

{{$duration['time_spent'] ?? '' }}

time_spent is in seconds. How do I convert it to hours in human readable

For instance, 4 Hours 20 Minutes

time_spent is something like: 124323.4

When I did

{{$duration['time_spent']->diffForHumans() ?? '' }}

I got this error:

Call to a member function diffForHumans() on float

How do I resolve it?

Thanks

Mar
29
2 months ago
Activity icon

Replied to Search Submit Is Not Redirecting To The Next Blade

@michaloravec - It works when I added this:

<script>
     document.getElementById("formSubmit").submit();
</script>

and hit enter key.

But I still want it to work when I click on

<input class="search-field" type="search" name="search" id="search" placeholder="client id...">
Activity icon

Replied to Search Submit Is Not Redirecting To The Next Blade

I'm so sorry @michaloravec. It's still not redirecting

Activity icon

Started a new Conversation Search Submit Is Not Redirecting To The Next Blade

In my Laravel-5.8, I am using the index as the search page:

public function index()
{
    $search = '';
    if (request('search'))
    {
        $search = request('search');

        return redirect()->route('client', [$search]);
    }
    return view('index', ['search' => $search]);
}

public  function client($clientid)
{
  $myparam = $clientid; 
  $client = new Client();
  $res = $client->request('GET','https://example/{$myparam}', [
    'query' => ['key' => 'jkkffd091']
   ])->getBody();
  $geoLocation = json_decode($res->getContents(), true);
  return view('client', [
     'geoLocation' => $geoLocation
  ]);
}

Here is my index blade:

<form method="GET" action="{{ route('index', ['search' => $search]) }}">

  <div class="field">
    <label class="label blog-sidebar-label" for="search">
            <input class="search-field" type="search" name="search" id="search" placeholder="client id..." value="{{ $search }}">
        </label>
  </div>
</form>

I have this route:

Route::get('/', [HomeController::class, 'index'])->name('index');
Route::get('client/{search}', [HomeController::class, 'client'])->name('client');

What I want to achieve is that when the search button for index is submitted with the clientid in the text input field, it should take the clientid as parameter and pass it to client controller. Also redirect to client blade. Then when nothing is in the text input field, it should indicate.

But it is not redirecting. How do I achieve this?

Thanks

Mar
27
2 months ago
Activity icon

Started a new Conversation How To Add Select All Option To Select Dropdown

In my Laravel-5.8, I have this code to filter reports by leave_type using dropdown

Controller:

 $leavetypes = HrLeaveType::where('company_id', $userCompany)->pluck('leave_type_name','id');
 if ($request->isMethod('post'))
 {
    $rules = [
        'leave_type_id'      => 'required|integer',
    ];
    $this->validate($request, $rules);
    $leave_type_id = $request->input('leave_type_id');
    if ($request->has('search'))
    {
     // select search
     $searchReports = DB::table('hr_leave_types AS lt')
        ->join('hr_leave_type_details AS ltd', 'lt.id', '=', 'ltd.leave_type_id')
        ->where('lt.id', $leave_type_id)
        ->select(
            'lt.leave_type_name',
            'lt.description',
            'ltd.no_of_days',
             )
        ->get();
      return view('report.leavereport',['searchReports' => $searchReports]);
   }
}
   return view('report.leavereport', ['leavetypes' => $leavetypes]);

View Blade:

<form novalidate action="{{route('report.leavereport')}}" method="POST" enctype="multipart/form-data">
<select class="form-control select2bs4" data-placeholder="Select Leave Type" tabindex="1" name="leave_type_id">
  <option value="">Select Leave Type</option>
  @if($leavetypes->count() > 0 ) @foreach ($leavetypes as $ids => $name)
  <option value="{{ $ids }}" {{ request( 'leave_type_id')==$ids ? 'selected' : ''}}>{{ $name }}</option>
  @endforeach @endif
</select>
<button type="submit" class="btn btn-primary btn-sm" name="search" >Search</button>
</form>

From the code, I filter by leavetype

In my view blade, I want the select dropdown to have "Select All" so that I can also display all the records for all leave_types.

How do I achieve this in my view blade and controller?

Thanks

Activity icon

Replied to How To Get Registered Student Per Class In The Current Year

The first part is sorted out. I changed:

DB::raw('COALESCE(COUNT("r.id"), "0") AS total_registered'),

to

DB::raw('COALESCE(COUNT(r.id), "0") AS total_registered'),
Mar
26
2 months ago
Activity icon

Started a new Conversation How To Get Registered Student Per Class In The Current Year

In my Laravel-5.8 application, I have these four (4) tables:

CREATE TABLE `my_classes` (
 `id` int(11) UNSIGNED NOT NULL,
 `school_id` int(11) DEFAULT NULL,
 `class_name` varchar(150) COLLATE utf8mb4_unicode_ci NOT NULL,
 `class_head_id` int(11) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

CREATE TABLE `students` (
 `id` int(11) NOT NULL,
 `student_code` varchar(50) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `school_id` int(11) NOT NULL,
 `first_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
 `last_name` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;


CREATE TABLE `registrations` (
 `id` int(11) UNSIGNED NOT NULL,
 `school_id` int(11) DEFAULT NULL,
 `registration_id` int(11) DEFAULT NULL,
 `student_id` bigint(20) UNSIGNED DEFAULT NULL,
 `registered_date` date NOT NULL,
 `is_registered` tinyint(1) DEFAULT 0 COMMENT '0=No,1=Yes',
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `registration_types` (
 `id` int(11) UNSIGNED NOT NULL,
 `school_id` int(11) DEFAULT NULL,
 `registration_type` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

For each table, id is the Primary Key and it's auto-increment. Each class have one class head that is also a student. Each student belong to a class and a class has many students. Each student register yearly. There are different registrations but the compulsory on is called "Core".

See the models:

class MyClass extends Model
{
    protected $table = 'my_classes';
    protected $fillable = [
	'id',
        'school_id',
        'class_name',
        'class_head_id',
    ];

    public function classhead()
    {
        return $this->belongsTo('App\Models\ClassHead','class_head_id','id');
    } 
}
class Student extends Model
{
    protected $table = 'students';
    protected $fillable = [
	'id',
        'school_id',
        'first_name',
        'last_name',
        'class_id',
    ];
    public function myclass()
    {
        return $this->belongsTo('App\Models\MyClass', 'class_id', 'id');
    }  
}
class RegistrationType extends Model
{
    protected $table = 'registration_types';
    protected $fillable = [
	  'id',
      'school_id',
	  'registration_type',
    ];

    public function registration(){
        return $this->hasMany('App\Models\Registration');
    } 
}
class Registration extends Model
{
    protected $table = 'registrations';
    protected $fillable = [
	'id',
        'school_id',
        'is_registered',
        'student_id',
	'registration_id',
	'registration_date',
    ];

    public function student()
    {
        return $this->belongsTo('App\Models\Student','student_id');
    } 

    public function registrationtype()
    {
        return $this->belongsTo('App\Models\RegistrationType','registration_type_id');
    }
}

I have this code in the controller:

$school = Auth::user()->school_id;
$registrationTypeName = "Core";

$studentRegistrations = DB::table('my_classess AS c')
   ->leftJoin('students AS ch', function($join) use ($school)
   {
   $join->on('ch.id', '=', 'c.class_head_id')
   ->where('ch.school_id', '=', $school);
   })
   ->leftJoin('students AS s', function($join) use ($student)
   {
   $join->on('c.id', '=', 's.class_id')
   ->where('s.school_id', '=', $school);
   })
   ->leftJoin('registrations AS r', function($join) use ($school)
   {
   $join->on('s.id', '=', 'r.student_id')
   ->where('r.company_id', '=', $school)
   ->where('r.is_registered', '1');
   })
   ->join('registration_types AS rt', function($join) use ($school, $registrationTypeName)
   {
   $join->on('r.registration_type_id', '=', 'rt.id')
   ->where('rt.school_id', '=', $school)
   ->where('rt.registration_type', 'LIKE', '%'.$registrationTypeName.'%');
    })
    ->where('c.school_id', '=', $school)
    ->select(
             'c.class_name',
              DB::raw('COALESCE(CONCAT(ch.first_name, " ", ch.last_name), "None") AS class_head'),
              DB::raw('COALESCE(COUNT("r.id"), "0") AS total_registered'),
            )
            ->groupby('c.id')
            ->get();

In my controller, I want to run a query that will display all the classes, Class Head, Total Registered, Total Not Registered. If there are not records of registration for any class, it should use 0. Also,

Total Registered = COUNT("r.id") where where('r.is_registered', '1') and registration_date is current year.

Total Not Registered = Total student per class - Total Registered

Everything should look like this:

Classes | Class Head | Total Registered | Total Not Registred

I have two problems:

  1. It's giving me total student per department for Total Registered instead

  2. How do I get Total Not Registred (Total Not Registered = Total student per class - Total Registered )?

Thanks

Mar
25
2 months ago
Activity icon

Started a new Conversation How To Do Leave Count Per Department

I am using Laravel-5.8 to get the count of employees that have applied for leave and those that have not applied for a particular year.

I have these 3 tables: hr_employees, hr_departments and hr_leave_requests.

class HrDepartment extends Model
{
  protected $table = 'hr_departments';
  protected $fillable = [
	  'id',
      'company_id',
      'dept_name',
    ];
}

class HrEmployee extends Model
{
  protected $table = 'hr_employees';
  protected $fillable = [
	  'id',
      'company_id',
      'first_name',
      'last_name',
      'department_id',
      ];
  public function department()
  {
      return $this->belongsTo('App\Models\Hr\HrDepartment','department_id','id');
  }  
}

class HrLeaveRequest extends Model
{
  protected $table = 'hr_leave_requests';
  protected $fillable = [
	  'id',
      'company_id',
      'leave_status',
      'employee_id',
    ];
  public function department()
  {
      return $this->belongsTo('App\Models\Hr\HrDepartment','department_id','id');
  }  
}

An employee can apply for a leave several times in a year, but it will be counted as one. A department has many employees. Here is my code below:

 $leaveReports = DB::table('hr_departments AS d')
    ->leftJoin('hr_employees AS e', function($join) use ($userCompany)
    {
     $join->on('d.id', '=', 'e.department_id')
     ->where('e.company_id', '=', $userCompany)
     ->where('e.hr_status', '=', '0');
    })
    ->join('hr_leave_requests AS lr', function($join) use ($userCompany)
    {
     $join->on('e.id', '=', 'lr.employee_id')
     ->where('lr.company_id', '=', $userCompany)
     ->where('lr.leave_status', '!=', '0');
     })
     ->where('d.company_id', '=', $userCompany)
     ->select(
        'd.dept_name',
         DB::raw('COUNT("lr.id") as applied_count'),
         )
     ->groupby('lr.employee_id')
     ->get();

I want to display the result below:

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

I want to list all the departments, count the number of employees that have applied for leave and those that have not. if leave_status is not 0, then employee_id has applied for leave. To get applied in a department, subtract total applied in that department from total employee in that department.

If I have 3 departments and 50 employees. It shows all the departments and show the count those that have applied and those not not applied per department

However, instead of get the type of result in the diagram, it calculated all the employees as total applied.

How do I resolve this?

Thanks

Mar
23
2 months ago
Activity icon

Replied to Laravel Search Between $from And $to Date Not Working

@snapey -It works when submitted at the first instance, but if I do the search again or any other one, it throws an error:

#0 C:\xampp\htdocs\myapp\vendor\

esbot\carbon\src\Carbon\Traits\Creator.php(645): Carbon\Carbon::rawCreateFromFormat('d-m-Y', NULL, NULL) #1 C:\xampp\htdocs\myapp\app\Http\Controllers\Report\LeaveReportsController.php(135): Carbon\Carbon::createFromFormat('d-m-Y', NULL)

and this is on the same line:

$from = Carbon::createFromFormat('d-m-Y', $request->input('from'));
Activity icon

Started a new Conversation Laravel - How To Retain The Datepicker Filter Value After Submit

In my Laravel-5.8, I use JQuery-UI datepicker to filter the table:

Controller:

if ($request->isMethod('post'))
{
    $from = Carbon::createFromFormat('d-m-Y', $request->input('from'));
    $to = Carbon::createFromFormat('d-m-Y', $request->input('to'));
    if ($request->has('search'))
    {
        // select search
        $searchReports = DB::table('hr_leave_requests AS lr')
            ->join('hr_leave_types AS lt', 'lr.leave_type_id', '=', 'lt.id')
            ->join('hr_employees AS em', 'lr.employee_id', '=', 'em.id')
            ->where('lr.leave_status', 4)
            ->where('lr.company_id', $userCompany)
            ->whereBetween('lr.commencement_date', [$from, $to])
            ->select('em.employee_code', DB::raw("CONCAT(em.first_name,' ',em.last_name) as full_name"), 'lr.commencement_date', 'lr.resumption_date', 'lr.no_of_days', 'lt.leave_type_name')
            ->get();

        return view('report.leave_reports.hr_leave_taken_by_date_report', ['searchReports' => $searchReports]);
    }

This is the view blade:

<script type="text/javascript">
  // $(document).ready(function() {
  $(function() {
    $('.fromDate').datepicker({
      dateFormat: 'dd-mm-yy',
      changeMonth: true,
      changeYear: true,
      showAnim: 'slideDown',
      duration: 'fast',
      yearRange: new Date().getFullYear() + ':' + new Date().getFullYear(),
    });
  });
</script>
<form action="{{route('reports.leaveReport')}}" method="POST" class="form-horizontal" enctype="multipart/form-data">
  @csrf
  <div class="container">
    <div class="row">
      <label for="from" class="col-form-label">From:</label>
      <div class="col-md-3">
        <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="from" class="form-control fromDate">
        </div>
      </div>
      <label for="from" class="col-form-label">To:</label>
      <div class="col-md-3">
        <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="to" class="form-control fromDate">
        </div>
      </div>
      <div class="col-md-4">
        <button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>
      </div>
    </div>
  </div>
</form>

I am using JQuery UI datepicker and commencement_date for $from and $to.

When I submitted the form with the search button, the values in the JQueru-UI datepickers ($from and $to) are cleared.

How do I retain these values

How do I resolve this?

Thanks

Activity icon

Replied to Laravel Search Between $from And $to Date Not Working

@tykus - When I used:

 $from = Carbon::createFromFormat('dd-mm-yy', $request->input('from'));
 $to = Carbon::createFromFormat('dd-mm-yy', $request->input('to'));

I got this error:

#0 C:\xampp\htdocs\myapp\vendor\esbot\carbon\src\Carbon\Traits\Creator.php(645): Carbon\Carbon::rawCreateFromFormat('dd-mm-yy', '01-03-2021', NULL)
#1 C:\xampp\htdocs\myapp\app\Http\Controllers\Report\LeaveReportsController.php(136): Carbon\Carbon::createFromFormat('dd-mm-yy', '01-03-2021')

In the database the date appears this way: 2021-03-15

Mar
22
2 months ago
Activity icon

Started a new Conversation Laravel Search Between $from And $to Date Not Working

In my Laravel-5.8, I have this code:

Controller:

    if ($request->isMethod('post'))
    {
        $from = $request->input('from');
        $to   = $request->input('to');
        if ($request->has('search'))
        {
            // select search
            $searchReports = DB::table('hr_leave_requests AS lr')
                    ->join('hr_leave_types AS lt', 'lr.leave_type_id', '=', 'lt.id')
                    ->join('hr_employees AS em', 'lr.employee_id', '=', 'em.id')
                    ->where('lr.leave_status', 4)
                    ->where('lr.company_id', $userCompany)
                    ->whereBetween('lr.commencement_date', [$from, $to])
                    ->select('em.employee_code',DB::raw("CONCAT(em.first_name,' ',em.last_name) as full_name"),'lr.commencement_date','lr.resumption_date','lr.no_of_days','lt.leave_type_name')
                    ->get();
            return view('report.leave_reports.hr_leave_taken_by_date_report',['searchReports' => $searchReports]);
        }

This is the view blade:

< script type = "text/javascript" >
  //        $(document).ready(function() {
  $(function() {
    $('.fromDate').datepicker({
      dateFormat: 'dd-mm-yy',
      changeMonth: true,
      changeYear: true,
      showAnim: 'slideDown',
      duration: 'fast',
      yearRange: new Date().getFullYear() + ':' + new Date().getFullYear(),

    });

  }); <
/script>
<form action="{{route('reports.leaveReport')}}" method="POST" class="form-horizontal" enctype="multipart/form-data">
  @csrf
  <div class="container">
    <div class="row">
      <label for="from" class="col-form-label">From:</label>
      <div class="col-md-3">
        <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="from" class="form-control fromDate">
        </div>
      </div>
      <label for="from" class="col-form-label">To:</label>
      <div class="col-md-3">
        <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="to" class="form-control fromDate">
        </div>
      </div>

      <div class="col-md-4">
        <button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>

      </div>
    </div>
  </div>
</form>

Route:

    Route::get('reports/leaveReport', '[email protected]')->name('reports.leaveReport');
    Route::post('reports/leaveReport', '[email protected]')->name('reports.leave');

I am using JQuery-UI datepicker.

I am using commencement_date for $from and $to. As I select #from and $to and submit, I expect it to filter according to the selected date, but nothing is displayed.

If I remove the $from and $to and load it directly on the view blade, it works fine.

How do I resolve this?

Thanks

Activity icon

Started a new Conversation Resumption_date Calculation Fail In JQuery-UI Datepicker

In my Laravel-5.8 application, I am using JQuery-UI datepicker for the commencement_date and resumption_date.

Then, I pass the holidays from the controller to view as json:

  $nationalholidays = HrHolidayDate::select('holiday_date')
    ->whereYear('created_at', '=', datea'Y'))
    ->get()
    ->map(function ($nationalholiday) {
      return DateTime::createFromFormat('Y-m-d h:i:s', $nationalholiday->holiday_date)
            ->format('Y-m-d');
   });
      return response()->json([
             'nationalholidays' => $nationalholidays,
   ]);

My JQuery for the resumption_date calculation is as shown below:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

   < script type = "text/javascript" >
     $(document).ready(function() {
       $("#leave_days").on('keyup blur', function(e) {
         var periodval = parseInt($("#leave_days").val());
         holidayDays = holidayDays;
         var startDate = $('.commencement_date').datepicker("getDate");
         var endDate = $('.resumption_date');
         var date = new Date(startDate);
         var newdate = new Date(date);
         var cDate = $('.commencement_date');
         var rDate = $('.resumption_date');
         var dte = cDate.datepicker("getDate");

         if (weekendInclusives == 0 && holidayInclusives == 0) {
           for (i = 0; i < periodval; i++) {
             var date = newdate.getDate();
             var month = newdate.getMonth() + 1; 
             var year = newdate.getFullYear();
             var cun_date = year + '-' + month + '-' + date;
              for (j = 0; j < holidayDays.length; j++) {
                if (is_weekend(newdate) == "weekend") {
                   if (holidayDays[j] == cun_date) {
                     var skip_day = 1;
                     break;
                 } else {
                  var skip_day = 1;
                 }
               } else if (holidayDays[j] == cun_date) {
                 var skip_day = 1;
                 break;
               } else {
                 var skip_day = 0;
               }
             }
             if (skip_day == 1) {
               newdate.setDate(newdate.getDate() + 1);
               i--;
             } else if (skip_day == 0) {
               newdate.setDate(newdate.getDate() + 1);
             }
           }
            var dd = newdate.getDate();
            var mm = newdate.getMonth() + 1;
            var y = newdate.getFullYear();
            var someFormattedDate = dd + '-' + mm + '-' + y;
            document.getElementById('resumption_date').value = someFormattedDate;
            } else {
             dte.setDate(dte.getDate() + periodval);
             rDate.datepicker("setDate", dte);
         }
         });
       }); 
    </script>

And here is the view blade for the commencement_date, resumption_date and no_of_days:

   <!-- language: lang-html -->

    <input type="hidden" id="available_leave_daysx" class="form-control" value="0">
    <input type="text" id="weekendinclusive" name="weekend_inclusive" class="form-control">
    <input type="text" id="holidayinclusive" name="holiday_inclusive" class="form-control">
    <input type="hidden" id="nationalholidays" name="national_holiday" class="form-control">

    <div class="col-sm-4">
      <div class="form-group">
       <label>Commencement Date:<span style="color:red;">*</span></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" id="commencement_date" class="form-control commencement_date" placeholder="dd/mm/yyyy" readonly autocomplete="off" name="commencement_date" value="{{old('commencement_date')}}">
        </div>

      </div>
    </div>
    <div class="col-sm-4">
      <div class="form-group">
        <label>Leave Days:<span style="color:red;">*</span></label><input type="hidden" id="leave_balance" value="0" disabled>
        <input type="text" id="leave_days" name="no_of_days" class="form-control no_of_days" placeholder="e.g. 10" value="{{old('no_of_days')}}" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" style="width: 100%;"
      maxlength="3" onkeyup="checkScore(this.value)" onkeypress="allowNumbersOnly(event)">
      </div>
    </div>
    <div class="col-sm-4">
      <div class="form-group">
        <label>Resumption Date:</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" id="resumption_date" class="form-control resumption_date" placeholder="dd/mm/yyyy" readonly autocomplete="off" name="resumption_date" value="{{old('resumption_date')}}">
     </div>
     </div>
    </div>

<!-- end snippet -->

console.log(holidayDays);

gives something like:

create:770 (2) ["2021-03-24", "2021-07-08"]0: "2021-03-24"1: "2021-07-08"length: 2__proto__: Array(0)

What I want to achieve is this: on leave_days keyup, no_of_days is added to commencement_date to give resumption_date

The issue I have is from:

if (weekendInclusives == 0 && holidayInclusives == 0) {

Whenever console.log(holidayDays); is not empty, I get the correct result. But whenever console.log(holidayDays); is empty (when there's no national holiday), that is when it is []

resumption_date does not change on leave_days keyup.

How do I correct this?

Thanks

Mar
18
2 months ago
Activity icon

Started a new Conversation How To Combine SortBy And GroupBy In Laravel Collection

I am consuming external API in Laravel-5.8 using Guzzle:

public  function index()
{
    try{
    $client = new Client();
    $res = $client->request('GET','https://example.com/tracking/JKK998', [
       'query' => ['key' => 'jkkkm7725']
   ])->getBody();
    $geoLocation = json_decode($res->getContents(), true);
    $currentLocationGroup = collect($geoLocation)->groupBy(function ($data) {
        return Carbon::parse($data['current_timestamp'])->format('d-m-Y');
    })->all();        
    return view('index', [
        'currentLocationGroup' => $currentLocationGroup,
        'geoLocation' => $geoLocation
    ]);
    }catch (Exception $exception) {
        Log::error($exception);
        return back();
    }
}

How do I combine sortBy() and groupBy() in $currentLocationGroup for current_timestamp?

Thanks

Activity icon

Replied to Undefined Index: Current_timestamp In Nested Foreach

@tykus - Everything displays todays date for the 15 items in $groupValue while

@foreach($geoLocationData as $value)

did not display anything at all.

Activity icon

Replied to Undefined Index: Current_timestamp In Nested Foreach

@tykus - When I did data_get($groupValue, 'current_timestamp')

<span class="bg-red">{{ \Carbon\Carbon::parse(data_get($groupValue, 'current_timestamp'))->format('d-m-Y') }}</span>

displays today's date in 15 places. No other record was displayed.

It didn't even display any record for:

@foreach($geoLocationData as $value)
Activity icon

Started a new Conversation Undefined Index: Current_timestamp In Nested Foreach

In my Laravel-5.8, I am trying to use Nested foreach statement in the view blade:

I have this controller:

public  function index()
{
    try{
    $client = new Client();
    $res = $client->request('GET','https://example.com/tracking/JKK998', [
       'query' => ['key' => 'jkkkm7725']
   ])->getBody();
    $geoLocation = json_decode($res->getContents(), true);
    $geoLocationData = collect($geoLocation)->sortBy(function ($data) {
        return Carbon::parse($data['current_timestamp'])->format('d-m-Y h:i:s');
    })->all(); 
    $currentLocation = collect($geoLocation)->sortByDesc(function ($data) {
        return Carbon::parse($data['current_timestamp'])->format('d-m-Y h:i:s');
    })->first(); 
    $currentLocationGroup = collect($geoLocation)->groupBy(function ($data) {
        return Carbon::parse($data['current_timestamp'])->format('d-m-Y');
    })->all();        
    $currentLocationFilter = explode(',', $currentLocation['current_coord'] ?? '');
    return view('index', [
        'currentLocation' => $currentLocation,
        'currentLocationGroup' => $currentLocationGroup,
        'currentLocationFilter' => $currentLocationFilter,
        'geoLocation' => $geoLocation,
        'geoLocationData' => $geoLocationData
    ]);
    }catch (Exception $exception) {
        Log::error($exception);
        return back();
    }
}

dd($currentLocationGroup);

gives:

array:14 [▼
  "22-06-2020" => Illuminate\Support\Collection {#297 ▼
    #items: array:25 [▼
      0 => array:30 [▼
        "current_timestamp" => "2020-06-22T11:53:29Z"
        "trip_status" => "DISPATCHED"
      ]
      1 => array:31 [▶]
      2 => array:31 [▶]
      ...

While dd($geoLocationData); gives:

array:554 [▼
 0 => array:30 [▼
  "current_timestamp" => "2021-01-22T12:30:25.4698261Z"
  "client_tracking_id" => "ddd3321"
  "current_asset_position_name" => "2, Adelaide, Australia"
  "trip_status" => "DISPATCHED"
]
1 => array:31 [▼
  "current_timestamp" => "2021-02-23T20:51:50.3066741Z"
  "client_tracking_id" => "TRIP-20200621007"
  "current_asset_position_name" => "20, Adelaide, Australia"
  "trip_status" => "AROUND CUSTOMER LOCATION"
]
....

View blade:

@foreach($currentLocationGroup as $groupValue)
<div class="time-label">
  <span class="bg-red">{{ \Carbon\Carbon::parse($groupValue['current_timestamp'])->format('d-m-Y') }}</span>
</div>
@foreach($geoLocationData as $value) 
 @if(\Carbon\Carbon::parse($groupValue['current_timestamp'])->format('d-m-Y') == \Carbon\Carbon::parse($value['current_timestamp'])->format('d-m-Y') )
<div>
  <i class="fas fa-truck bg-green"></i>
  <div class="timeline-item">
    <span class="time"><i class="fas fa-clock"></i> {{ \Carbon\Carbon::parse($value['current_timestamp'])->diffForHumans() ?? 'N/A' }}</span>
    <h3 class="timeline-header no-border">Trip Status: {{ $value['trip_status'] }} </h3>
    <div class="timeline-body">
      <p>Location: <b>{{ $value['current_name'] ?? '' }}</b></p>
      <p>Time: <b>{{ \Carbon\Carbon::parse($value['current_timestamp'])->format('d-m-Y h:i:sA') ?? 'N/A'  }}</b></p>
    </div>
  </div>
</div>
@endif 

endforeach

But I got this error:

ErrorException Undefined index: current_timestamp

C:\xampp\htdocs\tracking-app\vendor\laravel\framework\src\Illuminate\Collections\Collection.php:1414

public function offsetExists($key)
{
    return isset($this->items[$key]);
}

But it exists.

The issue is with $currentLocationGroup. Because $geoLocationData is working fine when I removed $currentLocationGroup. from the view blade

How do I get this resolved?

Thanks

Activity icon

Started a new Conversation How To Get Find Current Address Or Town From Latitude And Longitude

I am using Laravel-5.8 and Guzzle to consume an external api:

public  function index()
{
    try{
    $client = new Client();
    $res = $client->request('GET','https://examplet/tracking/JKK123', [
       'query' => ['key' => 'jkkffd091']
   ])->getBody();
    $geoLocation = json_decode($res->getContents(), true);
    $currentLocation = collect($geoLocation)->sortByDesc(function ($data) {
        return Carbon::parse($data['Timestamp'])->format('d-m-Y h:i:s');
    })->first();  

    $currentLocationFilter = explode(',', $currentLocation['current_asset_position_coord'] ?? '');
    dd($currentLocationFilter);
    return view('index', [
        'currentLocation' => $currentLocation,
        'currentLocationFilter' => $currentLocationFilter,
        'geoLocation' => $geoLocation
    ]);
    }catch (Exception $exception) {
        Log::error($exception);
        return back();
    }
}

dd($currentLocationFilter);

gives me the Latitude and Longitude like this:

array:2 [▼
  0 => "2.1234565432145"
  1 => "1.7864321249555"
]

How do I translate this on my view blade into the Name of the Town or Current Address

  <th>
       Town Name/Current Address
  </th>
  <td>
                   
  </td>

Thanks

Mar
16
2 months ago
Activity icon

Started a new Conversation How To Display Create Button Based Created_at For Current Year

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

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

      $currentStatus = HrLeaveRequest::select('leave_status')->where('employee_id', $userId)->where('is_resumption_activated', 1)->whereIn('leave_status', array(3, 4))->orderBy('created_at', 'DESC')->first();
      return view('leave.index')
              ->with('currentStatus', $currentStatus);
}

view blade

         @if ($currentstatus)

        <div style="margin-bottom: 10px;" class="row">
            <div class="col-lg-12">
                <a class="btn btn-info" href="{{ route("leave.create") }}">
                    Create Leave
                </a>
            </div>
        </div>
         @elseif (! $currentstatus)
        <div style="margin-bottom: 10px;" class="row">

        </div>
        @endif

From the code above I want "Create Leave" to only be displayed where:

(

employee_id= $userId,

is_resumption_activated=1,

whereIn(leave_status,array(3,4)

)

OR

(

employee_id= $userId,

whereIn(leave_status,array(3,4),

whereYear('created_at',date('Y'))

)

How do I combine these two queries separated by OR in $currentStatus and everything enclosed in orderBy('created_at', 'DESC')->first()

Mar
09
3 months ago
Activity icon

Replied to How To Update A Table Using Maatwebsite Excel Import Based On Condition

@neilstee - I changed it to collection.

class FirstEmployeeSheetImport implements ToCollection, WithHeadingRow, SkipsOnError, WithValidation, SkipsOnFailure
{
   use Importable, SkipsErrors, SkipsFailures;

  public function collection(Collection $rows)
   {           
    foreach ($rows as $row) 
    {
      $this->department = $row['department'];        
        HrEmployee::where('company_id', auth()->user()->company_id)
            ->where('employee_code', $row['staff_id'])
            ->where('email', $row['official_email'])     
            ->update([
               'department_id' =>$this->getDepartment(),
            ]);                
       }    
   }

   public function getDepartment(){
    if(!empty($this->department) || !$this->department){

        return HrDepartment::where('dept_name',$this->department)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
    } else {
        return 0;
    }
  }              
}

When there is no failure, it updates the department_id for each employee. But when there is failure, like if the email or employee_code not provided or not well validated. It skips the failed rows, but shows success and still did not display the page having the error.

Activity icon

Started a new Conversation How To Update A Table Using Maatwebsite Excel Import Based On Condition

In my Laravel-5.8 and Maatwebsite-3.1, I have a table called employees (Employee).

class FirstEmployeeSheetImport implements ToModel, WithBatchInserts, WithHeadingRow, SkipsOnError, WithValidation, SkipsOnFailure
{
   use Importable, SkipsErrors, SkipsFailures;

   public function model(array $row)
   {           
      $this->department = $row['department'];        
       return new Department([
        'employee_code'                     => $row['employee_code'],
        'company_id'                        => Auth::user()->company_id,
        'email'                                   => $row['official_email'],
        'department_id'                     => $this->getDepartment(),
     ]);                
           
   }

   public function getDepartment(){
    if(!empty($this->department) || !$this->department){

        return HrDepartment::where('dept_name',$this->department)->where('company_id',Auth::user()->company_id)->pluck('id')->first();
    } else {
        return 0;
    }
  }              
}

I want to use the excel upload to update these two (2) fields: email and department_id for each of the employees where:

company_id = Auth::user()->company_id AND employee_code = $row['employee_code']. AND email = $row['official_email']

Also, it should only perform the update for those that meet the condition. I should only perform update and don't crete.

How do I achieve this?

Thanks

Mar
06
3 months ago
Activity icon

Replied to Maatwebsite Import On Failure Redirects To Login Page

@neilstee - Thanks. Let me go over it again