Laravel – Call database seeder class from controller
Some times you may need to see the results of specific seeder class in a web page instead of terminal.
Thus instead of calling the seeder class via terminal:
1 2 3 4 |
php artisan db:seed --class="ClassName" |
Call the class from within a controller, and here is the way I used to achieve that:
First, inside your seeder class add the namespace you want, I do that by writing the folders as namespace.
UserSeeder
1 2 3 4 5 |
<?php namespace Database\Seeds; // This line need to be added as first line, choose whatever namespace... |
UserController
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php namespace App\Http\Controllers; use App\Http\Controllers\Controller As Controller; use Database\Seeds\UserSeeder; // First line #1 class UserController extends Controller { public function seedDemoUsers() { $userSeeder = new UserSeeder(); // Second line #2 } ... } |
Very Important to know that this affect the seeder class, now if you want to use DB Facade earlier you got it by default, but now you must add it to your seeder manually/strong>, the same for Log Facade and other Facades…
1 2 3 4 5 |
use DB; // Inside your seeder class |
Errors
If you are going to use the same seeder in terminal after doing the above changes you will get this error:
ReflectionException : Class StreetSeeder does not exist
And this happens because now Laravel does not recognize the seeder class because of the new namespace you added.
To Fix the error
1 2 3 4 5 |
// In terminal: php artisan db:seed --class="Database\Seeds\StreetSeeder" |
Thanks for reading