Search code examples
laraveleloquentlaravel-5.3predis

What is the correct way to update / delete / insert a record into MySQL and Predis together in Laravel


I am starting with Laravel Predis and Redis. The question is, what's the best way to handle a update in Laravel and Redis together? Is this the best way or can t be done simpler?

Eloquent update:

    $article = Article::find(1);
    $article->title         = Input::get('title');
    $article->save();

Redis Hmset:

    $client = Redis::connection();
    $client->hmset('testtest', ['1'=> 'testtest']);

Solution

  • At laravel, creating a model is a must for you, this is a sample model for you:

    class Article extends Model
    {
        // set your table name from your database
        protected $table = 'articles';
    
        // set each field at table
        protected $fillable = [ 'title', 'content', 'status' ];
    }
    

    For Update:

    $article = Article::find(1);
    $article->update( [
        'title' => Input::get( 'title' ),
        'content' => Input::get( 'content' ),
        'status' => Input::get( 'status' ),
    ] );
    

    For automatically update when there's an update :

    protected static function boot() {
        parent::boot();
    
        static::updated( function( $article ) {
            $client = Redis::connection();
            $client->hmset('testtest', ['1'=> 'testtest']);
        });
    }