K
K
kiranananda2019-08-24 20:28:36
Laravel
kiranananda, 2019-08-24 20:28:36

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

1 answer(s)
K
kiranananda, 2019-08-24
@kiranananda

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];
    }    
}

Controller
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();
    }

The very rule of validation
public function passes($attribute, $value)
    {	
       return (app()->get(DriverLogin::class)) ? true : false;
    }

Inheritance of the original model. I have 2 service providers, one at the entrance, the other when the person logged in. That's what inheritance is for.
<?php

namespace App\Models;

class DriverLogin extends \Backend\Driver\Models\Driver
{

}

?>

As a result, this scheme is a little complicated for this situation, in real life I just did it like this
<?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;
  	}
}

?>

And from the right places I get the result of the request ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question