S
S
Sergey Gutovsky2018-05-25 19:08:06
Laravel
Sergey Gutovsky, 2018-05-25 19:08:06

How to update the database before the controllers start working?

When entering, let's say, any page, I need to check the database for overdue tasks and, if there are any, update some fields. You need to do this before you start running controllers and displaying views. I tried to use middleware, but then a problem popped up: a variable was taken from my GET request

function index(Skill $skill)
{
    ...
}

The fact is that first laravel finds this skill in the database, and then the work of the middleware begins, where it is updated and as a result, the "old" version of the model will be displayed on the page.
I tried to do it through the view composer in the provider and everything basically worked. But it seems to me that this is a crutch, because vc is needed, as I know, to send variables to certain views, and I just need to update the database.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yan-s, 2018-05-25
@Yan-s

Try to create your own service provider that will be responsible for checking tasks and updating fields, register it before RouteServiceProvider. Then the updates would have to happen before getting the model for the controller.

V
Vladislav Nagorny, 2018-05-27
@esvils

in Controller make a constructor

<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;

    public function __construct()
    {
        $this->middleware(function ($request, $next) {

            return $next($request);
        });
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question