Laravel – Call database seeder class from controller
Sometimes you may need to see the results of a specific seeder class on a web page instead of a 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 a 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 affects 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, 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 the 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
YOU NEED QUALITY VISITORS for your: stepintoprogramming.com
My name is Karen, and I’m a Web Traffic Specialist. I can get:
– visitors from search engines
– visitors from social media
– visitors from any country you want
– very low bounce rate & long visit duration
CLAIM YOUR 24 HOURS FREE TEST
ContactMe: ventfara@mail.com