Home > database >  How can I run the table seeders after the successful creation of the tables, in this Laravel app?
How can I run the table seeders after the successful creation of the tables, in this Laravel app?

Time:01-14

I am working on a blogging application in Laravel 8.

I am preparing it for deployment on a live server and I want the deployment process to be very user-friendly.

For this purpose, I have been working on an "installer" for the app:

In routes\web.php I have:

Route::get('/install', [InstallController::class, 'index']);

In app\Http\Controllers\InstallController.php I have this piece of code in order to run the migrations if there is no users table:

class InstallController extends Controller
{
    public function index() {
      if (!Schema::hasTable('users')) {
        Artisan::call('migrate'); 
      } 
      return redirect('/register')->with('success', 'Way to go! You can create an account.');
    }
}

The above code works, all the tables are created and the (first) user is invited to sign up.

The problem

The problem is that I have not found a way to make the controller run the database seeders after the successful creation of the tables.

How can I achieve this goal in an easy and friendly manner?

CodePudding user response:

You can do it by running php artisan db:seed or, through Artisan facade like Artisan::call('db:seed');

Your code will be:

class InstallController extends Controller
{
    public function index() {
      if (!Schema::hasTable('users')) {
        Artisan::call('migrate');
        Artisan::call('db:seed'); 
      } 
      return redirect('/register')->with('success', 'Way to go! You can create an account.');
    }
}

Source: https://laravel.com/docs/9.x/seeding#running-seeders

However, I'd suggest not to go this path, but rather create deployment script that will do all of this for you. As with this, you are exposing this route to all users that will be using the app, and malicious users can leverage it.

  • Related