Answer the question
In order to leave comments, you need to log in
How to properly implement model caching for rules?
Hello!
Something broke his whole head, how to do it correctly.
I have a bunch of different validation rules and some of them validate data in the same model. And if in each rule I make a request for a model from the database, and then I also make a request for this model from the controller, then I get, at the moment, 3 identical requests to the database. What is not good. What would be the correct way to implement this? Or is it okay to do this?
Answer the question
In order to leave comments, you need to log in
I implemented it like this, correct it if possible in a simpler or more correct way ...
Service provider
class DriverLoginServiceProvider extends ServiceProvider
{
// protected $defer = true;
public function register()
{
$this->app->singleton(DriverLogin::class, function ($app) {
return DriverLogin::where('phone', Request::input('phone', 'none'))->first();
});
}
public function provides()
{
return [DriverLogin::class];
}
}
public function loginCheckPhone(CheckDriver $request, DriverLogin $driver)
{
// Проверяем можно ли делать повторную отправку.
if ( ($checkSend = Sms::checkSend($driver->verify_code)) !== true ) {
return response()->json( $checkSend, 403);
}
$driver->verify_code = Sms::send($driver->phone, 'Ваш код авторизации в личном кабинете: %code');
$driver->save();
}
public function passes($attribute, $value)
{
return (app()->get(DriverLogin::class)) ? true : false;
}
<?php
namespace App\Models;
class DriverLogin extends \Backend\Driver\Models\Driver
{
}
?>
<?php
namespace App\Services;
use Backend\Driver\Models\Driver;
use Request;
class DriverLogin
{
private static $model = null;
public static function get()
{
if (DriverLogin::$model === null ) {
$phone = Request::input('phone', '');
DriverLogin::$model = (iconv_strlen($phone) != 12)
? false
: Driver::where('phone', $phone)->first();
}
return DriverLogin::$model;
}
}
?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question