Search code examples
laravelcronschedule

Laravel Using Schedule to create entries every week for multiple users


I am trying to auto generate multiple entries, one for each user every Monday morning at 07:00.

Also it needs to check that an entry doesn't exist as the users can create there own if needed, I already validate manual creation with Requests timesheetRequest.php

Console/Commands/AddSheets.php

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use Carbon\Carbon;
use DB;

class AddSheets extends Command
{
protected $signature = 'add:sheets';

protected $description = 'Generate new timesheet for all active users';

public function handle()
{
    /**
     * get users where active
     * if does not exist, create a new timesheet for each user for current week 2018-11 W/C 24-03 MS
     */
    $users = User::with('profile')->where('status_id', '1')->get();
    foreach ($users as $user) {
        $currentweek = Carbon::now()
            ->year . '-' . Carbon::now('w')
            ->weekOfYear . ' W/C ' . Carbon::now()
            ->day . '-' . Carbon::now()
            ->month . ' ' . $user->profile->code();
        DB::table('timesheets')->insert([
            'name' => $currentweek,
            'status_id' => 1,
            'user_id' => $user->id
        ]);
    }
    $this->info('Add:Sheets Command Run successfully!');
}
}

with

Kernel.php

<?php

namespace App\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Models\User;
use Carbon\Carbon;
use DB;

class Kernel extends ConsoleKernel
{

protected $commands = [
    Commands\AddSheets::class
];

protected function schedule(Schedule $schedule)
{
    $schedule->command('add:sheets')->weekly()->mondays('07:00');
}

protected function commands()
{
    require base_path('routes/console.php');
}
}

When I run

php artisan add:sheets

I get

In Builder.php line 2445:

Call to undefined method Illuminate\Database\Query\Builder::code()

But I am unsure what this means and can't see anything in the source code to suggest anything other than line 2445 is the error message for an exception.

I am now at a loss.

please help


Solution

  • Update this variable declaration:

    $currentweek = Carbon::now()
        ->year . '-' . Carbon::now('w')
        ->weekOfYear . ' W/C ' . Carbon::now()
        ->day . '-' . Carbon::now()
        ->month . ' ' . $user->profile->code(); // Here
    

    to

    $currentweek = Carbon::now()->format("y-W \W/C d-m") . ' ' . $user->profile->code();
    

    The error you are getting is because you are trying to use the code() method of the profile model and it doesn't exist, make sure you have said method on the correct object, if you are trying to access a property use $user->profile->code instead like this:

    $currentweek = Carbon::now()->format("y-W \W/C d-m") . ' ' . $user->profile->code;
    

    Hope this helps you.