Skip to content

Instantly share code, notes, and snippets.

@barbietunnie
Last active June 19, 2023 06:04
Show Gist options
  • Save barbietunnie/84a0a6c1f26acabed259efa5a0c6206e to your computer and use it in GitHub Desktop.
Save barbietunnie/84a0a6c1f26acabed259efa5a0c6206e to your computer and use it in GitHub Desktop.
MySQL Database User GRANT permissions for Laravel

MySQL Database User GRANT permissions for Laravel

For security reasons, you should probably grant select, delete, update and insert to your app user in production.

Have another user who can do alter, create, drop and index when running migrations.

If you run seeders in production, also grant select, insert and references to the migration user.

Yeah, 2 users, migrations are not always run in production everyday and this keeps more secure your database.

In your config/database.php file, have something like:

// This is the default the app is going to use for insert, delete, update, select
'prod' => array(
          'driver' => 'mysql',
          'host' => 'prod_server',
          'port' => '3306',
          'database' => 'prod_database',
          'username' => 'app_user',
          'password' => 'secret',
          'charset' => 'utf8',
          'collation' => 'utf8_unicode_ci',
          'prefix' => '',
      ),

 // This is meant to be used only when migrations need to be executed
'migrate' => array(
          'driver' => 'mysql',
          'host' => 'prod_server',
          'port' => '3306',
          'database' => 'prod_database',
          'username' => 'migrations_user',
          'password' => 'secret',
          'charset' => 'utf8',
          'collation' => 'utf8_unicode_ci',
          'prefix' => '',
      ),

As you can see both connections point to the same host and same database, but the username is different according to the security permissions granted to each one.

Now, when you are in artisan and want to migrate just do this:

    php artisan migrate --database=migrate

That way will connect to the same server but with the user credentials that only let create, drop, alter, index.

For the general use of the app it will use the "prod" connection if you set it to the default in your database.php configuration file as this:

    'default' => 'prod'

This may not be the most elegant solution, but it will work without you having to modify your connection credentials each time you want to run migrations on production server, you just have to add the --database=connection switch to the artisan migrate command.

Source: Laracasts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment