jeudi 1 février 2018

Laravel "function name must be a string" error on saving a model when code is executing second pass in a scheduled loop

I am running a daily schedule in Laravel 5.5 which selects matching Posts and runs a foreach loop that calls a static function in PostController, editing the Post model and saving it afterwards.

When the code is executed, everything works fine on the first loop with the first post, but on the second pass, I get the function name must be a string error on when the function attempts saving the model.

Here is the schedule in kernel.php

$schedule->call(function () {
    $posts = DB::table('post')
        ->where('finish_time', '<', Carbon::now()->toDateTimeString())
        ->where('status', '=', '1')
        ->where('expiry_processed_at', '=', null)
        ->get()->all();

    if(count($posts) > 0){
        foreach ($posts as $post){
            PostController::processExpiry($post->post_id);
        }
    }
})->everyMinute();

And here is the function it calls in PostController:

public static function processExpiry($post_id){
    $post = Study::find($post_id);
    $latestLicense = $post->licenses->last();

    $email = $post->user->email;
    $param = ['post' => $post];

    \Mail::send(['html' => 'emails.post_expiry', 'text' => 'emails.txt.post_expiry'], $param, function ($message) use ($email) {
        $message->to($email)
            ->subject(trans('email_subject.post_expiry'));
    });

    // Identify post as processed
    $post->expiry_processed_at = Carbon::now()->toDateTimeString();

    $validator = \Validator::make(
        $post->toArray(),
        $post->rules
    );
    try {
        $post->saveOrFail(); // This is the line where error occurs on second pass
    } catch (\Exception $e) {
        // catch is never triggered
        $messages = $e->getMessage();
        return (Object) array('status' => false, 'error_message' => 'Error saving post to database');
    }
    // return because same function can be called manually by user
    return (Object) array('status' => true);
}

Thank you for your help!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire