How to run Laravel's routes with shell script of linux? - php

I am using Laravel on centos 7,I have some routes that are used to initiate some data,like this:
Route::get('init-users', 'InitController#initUsers');
Route::get('init-roles', 'InitController#initRoles');
//...
//...
//...
I want to write a shell script file to run the routes above,what command should I use to do it?

While you could use curl to accomplish this, Laravel actually has built in functionality for this, called Seeding.
Essentially, you'd do something like this:
php artisan make:seeder UsersTableSeeder
Then edit your UsersTableSeeder file:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::table('users')->insert([
'name' => str_random(10),
'email' => str_random(10).'#gmail.com',
'password' => bcrypt('secret'),
]);
}
}
Then finally: php artisan db:seed
Follow the link above for more information about it, as I gave you a very basic example.

Related

Mocking filesystem for testing laravel artisan commands

kinda stumped on how to test this. I'm working on building a command line tool that allows for the artisan make commands to be used outside of a laravel application. The idea being that this would allow artisan make commands to be used for package development anywhere on a dev system. I've got a working prototype, so I wanted to start adding in tests. However I'm a bit stumped on how to get the artisan command to execute inside of a mock filesystem (using mikey179/vfsStream). This is my current code:
namespace Tests\Feature;
use Tests\TestCase;
use org\bovigo\vfs\vfsStream;
use org\bovigo\vfs\vfsStreamWrapper;
use Illuminate\Support\Facades\Artisan;
class ChannelCommandTest extends TestCase
{
protected function setUp(): void {
parent::setUp();
$structure = [
'src' => [],
'tests' => []
];
$this->root = vfsStream::setup('newPackage', null, $structure);
vfsStreamWrapper::register();
}
public function testChannelCommand(): void {
Artisan::call('make:channel', ['name' => 'newChannel']);
$this->assertFileExists('src/Channels/Broadcasting/newChannel.php');
}
}

How to seed pivot table in Laravel 5.4?

I am following a tutorial called Incremental API in laracasts by Jeffrey Way.
There is a different coding between Laravel 4 faker class seeding and laravel 5.4.
I still followed the same code lines from the tutorials "Seeders Reloaded". Now, I am stuck with "Class LessonTagTableSeeder does not exist"
TagTableSeeder
class TagsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$faker = Faker::create('App\Tag');
for($i=1; $i <= 10; $i++) {
DB::table('tags')->insert([
'name' => $faker->word,
'created_at' => \Carbon\Carbon::now(),
'updated_at' => \Carbon\Carbon::now(),
]);
}
}
LessonTagTableSeeder
use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use App\Lesson;
use App\Tag;
class LessonTagTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$faker = Faker::create();
$lessonIds = Lesson::pluck('id')->all();
$tagIds = Tag::pluck('id')->all();
for($i=1; $i <= 30; $i++) {
DB::table('lesson_tag')->insert([
'lesson_id' => $faker->randomElement($lessonIds),
'tag_id' => $faker->randomElement($tagIds)
]);
}
}
DatabaseSeeder
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
use App\Lesson;
use App\Tag;
use DB;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
DB::statement('SET FOREIGN_KEY_CHECKS=0');
Lesson::truncate();
Tag::truncate();
DB::table('lesson_tag')->truncate();
Model::unguard();
$this->call('LessonsTableSeeder');
$this->call('TagsTableSeeder');
$this->call('LessonTagTableSeeder');
DB::statement('SET FOREIGN_KEY_CHECKS=1');
}
I was able to seed TagsTableSeeder with php artisan db:seed --class=TagsTableSeeder
When i run "php artisan db:seed --class=LessonTagTableSeeder" , i am prompted with:
[ReflectionException]
Class LessonTagTableSeeder does not exist
Do you have any idea how to edit the code above? Any help is appreciated
When you make changes into the seeder files and it does not reflects your changes you need to run composer dump autoload.
you can use any one of the following commands
$ composer dump-autoload
$ composer du
$ composer dump
$ composer dump-autoload -o
Then try to run you command db:seed again and it reflects you changes.
what composer dump autoload do?
composer dump-autoload won’t download a thing. It just regenerates the list of all classes that need to be included in the project (autoload_classmap.php). Ideal for when you have a new class inside your project.
Ideally, you execute composer dump-autoload -o , for a faster load of your webpages. The only reason it is not default, is because it takes a bit longer to generate (but is only slightly noticeable)
Make sure the file is named as LessonTagTableSeeder.php and it's in the same directory as the other seeders. Then run this command:
composer du
After that try to execute the seeder again.
run this command and then try again
composer dump-autoload -o
Usually cache
php artisan cache:clear
composer update
php artisan serve
A pivot table, or association table, is a table which maps the relationship between two other tables, very useful for two tables which have a many-to-many relationship.
There are 3 critical lines of code which you supplied for the 'DatabaseSeeder':
$this->call('LessonsTableSeeder');
$this->call('TagsTableSeeder');
$this->call('LessonTagTableSeeder');
Based on what you wrote, you only ran the commands for the 'TagsTableSeeder' and the 'LessonTagTableSeeder'. You missed running the command for 'LessonsTableSeeder'.
In other words, you had records in the 'Tag' table, but none in the 'Lesson' table. Therefore there were no records associated between the two tables and SQL couldn't create a null association (pivot) table.
As a further note, the order of execution for seed operations is important when creating an association table. You must execute the seed command for the association table AFTER seeding the other two tables. The association table needs to know the unique identifiers in each of the other tables in order to create the relationships.

Laravel 5 make seed to database not working

I try to seed a user to the database but cannot. I could easely create the migration tables, so the problem is not in the connection to the database, but I cannot create a user, I get the "Class UsersTableSeeder does not exist" error. How can I solve it? (I use laravel 5.3)
Console Error
Here is my code:
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call(UsersTableSeeder::class);
}
}
UsersTableSeeder.php
<?php
use Illuminate\Database\Seeder;
use App/User;
use Illuminate\Support\Facades\DB;
class UsersTableSeeder extends Seeder
{
public function run()
{
\DB::table('users')->delete();
User::create([
'name' => 'lamin',
'email' => 'lamin#laravel.com',
'password' => bcrypt('lamin')
]);
}
}
Try to run composer dumpauto command and then run seeder again.
Run this command.
composer dump-autoload
It just regenerates the list of all classes that need to be included in the project

Laravel 5.3 Seeder - undefined method table?

I'm trying to learn Laravel, but it seems the documentation is written with faulty examples... I want to create a table migration, run it, and seed it with some content.
First:
php artisan make:migration create_projects_and_tasks_tables
With the following content:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProjectsAndTasksTables extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->default('');
$table->string('slug')->default('');
$table->timestamps();
});
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->integer('project_id')->unsigned()->default(0);
$table->foreign('project_id')->references('id')->on('projects')->onDelete('cascade');
$table->string('name')->default('');
$table->string('slug')->default('');
$table->boolean('completed')->default(false);
$table->text('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('tasks');
Schema::drop('projects');
}
}
It migrated Ok. So I want to seed the projects table.
First:
php artisan make:seeder ProjectsTableSeeder
The contents:
<?php
use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;
class ProjectsTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$projects = array(
['id' => 1, 'name' => 'Project 1', 'slug' => 'project-1', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 2, 'name' => 'Project 2', 'slug' => 'project-2', 'created_at' => new DateTime, 'updated_at' => new DateTime],
['id' => 3, 'name' => 'Project 3', 'slug' => 'project-3', 'created_at' => new DateTime, 'updated_at' => new DateTime]
);
DB::table('projects')->insert($projects);
}
}
All set, I tried to rollback the migration, migrate and seed it:
php artisan migrate:refresh --seed
Rolled back: 2016_09_28_160459_create_projects_and_tasks_tables
Rolled back: 2014_10_12_100000_create_password_resets_table
Rolled back: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_100000_create_password_resets_table
Migrated: 2016_09_28_160459_create_projects_and_tasks_tables
[Symfony\Component\Debug\Exception\FatalThrowableError]
Call to undefined method Illuminate\Database\MySqlConnection::setTable()
And that's it. My table is empty, and the method DB::table() seems to not exist anymore in the framework, even if the 5.3 docs shows it. What can I do?
I'm using the Laravel Homestead vagrant box, so php version or composer isn't the issue. I'm also using MySQL as my database driver.
Once you have written your seeder classes, you may use the db:seed Artisan command to seed your database. By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the --class option to specify a specific seeder class to run individually:
php artisan db:seed
php artisan db:seed --class=UsersTableSeeder
Also You Can provide a seeder class reference to call method of DatabaseSeeder.php file
php artisan db:seed
will run the DatabaseSeeder.php file and invoke the run() meothd
So here you can provide list of Seed source like follow
public function run()
{
$this->call(CountriesTableSeeder::class);
$this->call(VendorTypesTableSeeder::class);
}
Reference : seeding
By default, the --seed option when passed to the migrate:refresh command will run
{YOUR_APP}/database/seeds/DatabaseSeeder.php
The make:migration artisan command will create your seed, but it won't add the seeder to the DatabaseSeeder.php file. You'll need to manually do this.
However, if you want to specify a particular seeder with migrate:refresh, then use the --seeder=YourSeeder option.
Add the following to the top of your seeder class:
use Illuminate\Support\Facades\DB;
Somehow, DB is not within the scope.
I got the exact same error. This was caused by typo obviously. Try to compare all the dataseed tables with other tables. You might have put \DB::class instead of \DB::table.

Laravel Seeding error

I am trying to seed some info on my oneway table but evertime I run php artisan db:seed, an error would occur
{"error":{"type":"Symfony\\Component\\Debug\\Exception\\FatalErrorException","me
ssage":"Class 'Oneway' not found","file":"C:\\wamp\\www\\airlines\\app\\database
\\seeds\\OnewayTableSeeder.php","line":8}}
I have tried composer dump-autoload but still nothing happens. What seems to be the problem here?
Is it on my composer or my codes.
OnewayTableSeeder.php
<?php
class OnewayTableSeeder extends Seeder{
public function run()
{
DB::table('oneway')->delete();
Oneway::create(
array(
'destination-from'=>'Bacolod',
'destination-to'=>'Cebu',
'departure'=> \Carbon\Carbon::createFromDate(2014,10,01)->toDateTimeString(),
));
Oneway::create(
array(
'destination-from'=>'Tawi-Tawi',
'destination-to'=>'Cebu',
'departure'=> \Carbon\Carbon::createFromDate(2014,10,03)->toDateTimeString(),
));
Oneway::create(
array(
'destination-from'=>'Cebu',
'destination-to'=>'Dipolog',
'departure'=> \Carbon\Carbon::createFromDate(2014,10,16)->toDateTimeString(),
));
}
}
DatabaseSeeder.php
<?php
class DatabaseSeeder extends Seeder {
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Eloquent::unguard();
// $this->call('UserTableSeeder');
$this->call('OnewayTableSeeder');
}
}
There is someone else who had a similar problem with migrations.
Laravel 4 migration: class not found exception
This might just work for you.
Other than this, make sure you have a model for OneWay and also make sure that the seeder file is named exactly OnewayTableSeeder.php. Moreover try using this package fzaninotto/Faker
to seed your database. I know that the library isn't relevant to the question you asked but it comes in very handy.
Also I personally tried removing either the model or the seeder file and it gives me a different exception than yours. All I can find everywhere is that the seeder file was not included and you should run composer dump-autoload or composer dumpautoload. Try both of them just for the sake of it.

Categories