Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel / Lumen ReadOnly Model?

There are some tables in our system which are being fed using 3rd party APIs and our system is supposed only read data from them and never Insert or Update anything.

Is there any feature in Laravel/Lumen, where we can mention in the Model to disallow/disable insert/update queries like we have the option public $timestamps = false; to disable the timestamps?

The tables are in same database else we would have restricted based on MySQL user.

like image 302
Deepanshu Goyal Avatar asked Dec 14 '22 08:12

Deepanshu Goyal


2 Answers

There are a few ways.
OPTION 1: Probably the quickest is this "read-only" model trait. https://github.com/michaelachrisco/ReadOnlyTraitLaravel

It protects you from...

  • create
  • forceCreate
  • save
  • update
  • firstOrCreate
  • firstOrNew
  • delete
  • destroy
  • restore
  • forceDelete
  • performDeleteOnModel
  • push
  • finishSave
  • performUpdate
  • touch
  • insert
  • truncate

OPTION 2: A completely different way to do it is on the db config and model connection. So, this has 2 parts.

project/config/database.php Duplicate and tweak the db connection.

'mysql' => [
            'driver'         => 'mysql',
            'host'           => env('DB_HOST', '127.0.0.1'),
    ...
'readonly' => [
            'driver'         => 'mysql',
            'read' => [
                'host' => env('DB_HOST', '127.0.0.1')
            ],
            'write' => [
                'host' => 'this.will.404'
            ],
    ...

project/app/MyReadOnlyModel.php

class MyReadOnlyModel extends Model
{
    protected $connection  = 'readonly';
...
}

If you are caught in the trap of wanting the Model to be writable sometimes... I would suggest having 2 models on the same table.

app/Normal/MyModel.php

app/ReadOnly/MyModel.php

like image 54
Tarek Adam Avatar answered Dec 21 '22 14:12

Tarek Adam


The most secure way will be to create a second MySQL user with the readonly only on the tables.
Then in Laravel you can create a specific connection with the restricted MySQL user in your config/database.php.
Then in the Model specify the wanted connection through the protected $connection property.

like image 42
ml59 Avatar answered Dec 21 '22 16:12

ml59