search

Home  >  Q&A  >  body text

How to run data populator after successfully creating table in Laravel app?

I'm developing a blogging application in Laravel 8.

I'm preparing to deploy it on a live server, and I want the deployment process to be very user-friendly.

To this end, I have been developing an "installer" for the application:

In routes\web.php I have:

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

In app\Http\Controllers\InstallController.php I have this code in order to run the migration If there is no user 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 code above works, all tables are created and the (first) user is invited to register.

question

The problem is that I haven't found a way to have the controller run the database seeder after successfully creating the table.

How to achieve this in a simple and friendly way?

P粉764785924P粉764785924314 days ago552

reply all(1)I'll reply

  • P粉921165181

    P粉9211651812024-03-31 09:43:48

    You can do this by running php artisan db:seed or via the Artisan look and feel, such as 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-seeder

    However, I recommend not going this route and instead creating a deployment script that will do all of this for you. As such, you expose this route to all users who will use the application, and malicious users can exploit it.

    reply
    0
  • Cancelreply