How to run data populator after successfully creating table in Laravel app?
P粉764785924
P粉764785924 2024-03-30 19:16:25
0
1
373

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粉764785924
P粉764785924

reply all(1)
P粉921165181

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!