How to create a mysql db with Laravel - laravel

I'm using Laravel 5.2. I've setup my first migrations and I want to run them. From the video tutorial it doesn't explain how to create a mysql db. I know I can do this manually in phpmyadmin but is there a Laravel way to do it?
This will install the migrations table:
php artisan migrate:install
Is there a similar command that will create the DB?
I'm thinking the process should be:
php artisan DB:install (or similar command)
Install the migrations table:
php artisan migrate:install
Run the migrations:
php artisan migrate
and to rollback the migrations:
php artisan migrate:rollback

Nothing provided out of the box but you could make your own command that could do this for you:
php artisan make:console CreateDatabase
// Note, in 5.3 this is make:command
Then in app/Console/Commands you'll find CreateDatabase.php. Open that sucker up and let's make a few changes:
protected $name = "make:database";
// in Laravel 5.3 + it's protected $signature
Then down below in your file we need a new function:
protected function getArguments()
{
return [
['name', InputArgument::REQUIRED, 'The name of the database'],
];
}
Then we'll make another function called fire() which will be called upon invocation of the command:
public function fire()
{
DB::getConnection()->statement('CREATE DATABASE :schema', ['schema' => $this->argument('name')]);
}
And now you can just do this:
php artisan make:database newdb
Now you'll get a newdb database created for you based on your connection configuration.
Edit Forgot the most important part - you need to tell app\Console\Commands\Kernel.php about your new comand, make sure to add it to the protected $commands[] array.
protected $commands = [
///...,
App\Console\Commands\CreateDatabase::class
];

This answer might be useful if you are using different mysql connection also. I am writing code in laravel 5.5
Step:1 Create command
php artisan make:command CreateDatabaseCommand
Step:2 In app/Console/Kernel.php register the command
protected $commands = [
CreateDatabaseCommand::class
];
Step:3 Write logic in your CreateDatabaseCommand.php file
protected $signature = 'make:database {dbname} {connection?}';
public function handle()
{
try{
$dbname = $this->argument('dbname');
$connection = $this->hasArgument('connection') && $this->argument('connection') ? $this->argument('connection'): DB::connection()->getPDO()->getAttribute(PDO::ATTR_DRIVER_NAME);
$hasDb = DB::connection($connection)->select("SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = "."'".$dbname."'");
if(empty($hasDb)) {
DB::connection($connection)->select('CREATE DATABASE '. $dbname);
$this->info("Database '$dbname' created for '$connection' connection");
}
else {
$this->info("Database $dbname already exists for $connection connection");
}
}
catch (\Exception $e){
$this->error($e->getMessage());
}
}
That's all. Now run your command
php artisan make:database {your-database-name} {your-connection-name}:
Note :: You should use second argument only if you want to create database in any different connection from default mysql connection otherwise command will automatically take the default db connection
Hope this will help someone :)

If you're not going to use a Vagrant box or virtual machine for local development then you're going to have to install your database driver of choice and then create a new database.
To do that with MySQL from the command line run:
$ mysql -uroot -p
mysql> create database yourDatabaseName;
Then cp .env.example .env and update your database creds.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=yourDatabaseName
DB_USERNAME=root
DB_PASSWORD=root
You'll have set up the username and password to your database when you first installed the driver. After this you may have to php artisan key:generate and/or 'php artisan config:clearbutphp artisan migrate` should work. Below are some tutorial resources you may find helpful:
Initial database creation and seeding with Laravel 5
How to install MySQL on OSX

Vikash's response worked. (in Laravel 5.8)
Based on the response of Vikash:
How to create a mysql db with Laravel
I have created the following command which creates a MySQL database with the collation that you assign.
I have uploaded it to this GitHub repository
I hope it helps other developers.

You should create the DB, and set the connection parameters to it. Then, Laravel will access the DB and will run the migrations (make the tables) and the seeders.
You can found the parameters for php artisan migrate here: https://laravel.com/docs/5.2/migrations#running-migrations

You can create the database using Laravel Tinker. First configure the right DB_ settings in your .env file.
Then run the following commands:
php artisan tinker
$pdo = new PDO('mysql:host=' . env('DB_HOST'), env('DB_USERNAME'), env('DB_PASSWORD')));
$pdo->exec('CREATE DATABASE ' . env('DB_DATABASE'));
exit
As a one liner it looks like this:
php artisan tinker --execute="(new PDO('mysql:host=' . env('DB_HOST'), env('DB_USERNAME'), env('DB_PASSWORD')))->exec('CREATE DATABASE ' . env('DB_DATABASE'))"

you have to make your modal first and make its migration table also in order to make a database.
you should use: php artisan make:model -m command to make model and migration table. after that open your migration table in any texteditor to add the columns in your database table and then, use this command to migrate:
php artisan migrate

Related

When I run " php artisan migrate " in my project the following error occurs, How can I solve the error?

When I run " php artisan migrate " in my project the following error occurs, How can I solve the error?
Illuminate\Database\QueryException
could not find driver (SQL: select * from information_schema.tables where table_schema = tc_cse-infohub and table_name = migrations and table_type = 'BASE TABLE')
at F:\xammp\htdocs\github\TC_CSE-infoHub\vendor\laravel\framework\src\Illuminate\Database\Connection.php:712
708▕ // If an exception occurs when attempting to run a query, we'll format the error
709▕ // message to include the bindings with SQL, which will make this exception a
710▕ // lot more helpful to the developer instead of just the database's errors.
711▕ catch (Exception $e) {
➜ 712▕ throw new QueryException(
713▕ $query, $this->prepareBindings($bindings), $e
714▕ );
715▕ }
716▕ }
``
1 F:\xammp\htdocs\github\TC_CSE-infoHub\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70 PDOException::("could not find driver")
2 F:\xammp\htdocs\github\TC_CSE-infoHub\vendor\laravel\framework\src\Illuminate\Database\Connectors\Connector.php:70 PDO::__construct()
```
It could be the wrong mysql port number in your .env file. Check your .env file and make sure the port number matches the same one mysql is using, also the SQL passwords in your env file, because the laravel framework is rejecting the connection hence the error on your screen.
Edit: If you're using windows make sure your php / db extensions are enabled on your xampp / wampp configurations.
For example: ;extension=pdo_mysql.so //uncomment this line just remove ;
after that please try again for php artisan migrate
You should install PDO on your server. Edit your php.ini (look at your phpinfo(), "Loaded Configuration File" line, to find the php.ini file path). Find and uncomment the following line (remove the ; character):
;extension=pdo_mysql.so
After this restart the server and should be good to go.
Edit:
composer update
composer require doctrine/dbal
php artisan cache:clear
php artisan view:clear
php artisan route:clear
Check your .env file
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=dbname
DB_USERNAME=username
DB_PASSWORD=password
run php -m and see if it lists pdo
Firest of all, adding phpinfo to your code path find out your php.ini location
<?php
phpinfo();
?>
Since you have already uncommented MySQL extension, make sure to uncomment extension=php_pdo.dll as well in the php.ini and restart the Apache.
Before migration, make sure to run
php artisan cache:clear
php artisan view:clear
php artisan route:clear

How to generate "make:model -a" with directory for seeders and controller and migrate name?

How to generate "make:model -a" with directory for seeders and controller and migrate name?
Laravel Framework 8.44.0
I am generating a model php artisan make:model Blog/MyCategory -a and expect to see the following structure:
Controllers/Blog/MyCategoryController.php
Models/Blog/MyCategory.php
factories/Blog/MyCategory.php
mifrations/2021_06_01_042639_create_blog_my_categories_table.php
seeders/Blog/MyCategorySeeder.php
Execute the command php artisan make:model Blog/Category -a
Model created successfully.
Factory created successfully.
Created Migration: 2021_06_01_044253_create_my_categories_table
Seeder created successfully.
Controller created successfully.
but it creates
Controllers/MyCategoryController.php (NO)
Models/Blog/MyCategory.php (YES)
factories/Blog/MyCategory.php (YES)
mifrations/2021_06_01_042639_create_my_categories_table.php (NO)
seeders/MyCategorySeeder.php (NO)
This way I cannot generate two MyCategory.
Execute the command php artisan make:model Shop/MyCategory -a
Model created successfully.
Factory created successfully.
InvalidArgumentException
A CreateMyCategoriesTable class already exists.
at vendor/laravel/framework/src/Illuminate/Database/Migrations/MigrationCreator.php:102
Remove the
model Shop/MyCategory.php,
factory Shop/MyCategoryFactory.php
migration file 2021_06_01_044253_create_my_categories_table.php
Now let's create the correct migration file
php artisan make:migration CreateBlogMyCategoryTable
Again execute the command php artisan make:model Shop/MyCategory -a
Model created successfully.
Factory created successfully.
Created Migration: 2021_06_01_050039_create_my_categories_table
Seeder already exists!
Controller already exists!
It again creates a 2021_06_01_050039_create_my_categories_table file and does not take into account the model in the Shop directory
Remove generated files again:
model Shop/MyCategory.php
factory Shop/MyCategoryFactory.php
migration file 2021_06_01_050039_create_my_categories_table.php
controller MyCategoryController.php
Now let's create the correct migration and controllers:
php artisan make:migration CreateShopMyCategoryTable
php artisan make:controller Blog/MyCategoryController
php artisan make:controller Shop/MyCategoryController
Total
Thus, we see that the "-а" option is not suitable in this case. You need to create models, controllers and migrations separately.
php artisan make:controller Blog/MyCategoryController -r
php artisan make:controller Shop/MyCategoryController -r
php artisan make:migration CreateBlogMyCategoryTable
php artisan make:migration CreateShopMyCategoryTable
Model with factory
php artisan make:model Blog/MyCategory -f
php artisan make:model Shop/MyCategory -f
This command also makes the correct Factory
php artisan make:factory Blog\\MyCategoryFactory --model=Blog\\MyCategory
<?php
namespace Database\Factories\Blog;
use App\Models\Blog\MyCategory;
use Illuminate\Database\Eloquent\Factories\Factory;
class MyCategoryFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* #var string
*/
protected $model = MyCategory::class;
// ....
}
The migration files, models, and controllers as we need in the appropriate directories.
php artisan migrate
Migration table created successfully.
...
Migrating: 2021_06_01_055036_create_blog_my_category_table
Migrated: 2021_06_01_055036_create_blog_my_category_table (36.26ms)
Migrating: 2021_06_01_055541_create_shop_my_category_table
Migrated: 2021_06_01_055541_create_shop_my_category_table (39.16ms)
As I understand it, the required structure will still have to be done by separate commands.
But then another problem appeared: I do not understand how to use now factory()->create()
Route::get('/', function () {
\App\Models\Blog\MyCategory::factory(1)->create();
return view('welcome');
});
Illuminate\Database\QueryException
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'larablog.my_categories' doesn't exist (SQL: insert into `my_categories` (`updated_at`, `created_at`) values (2021-06-01 06:59:52, 2021-06-01 06:59:52))
or tinker
php artisan tinker
Psy Shell v0.10.8 (PHP 7.4.18 — cli) by Justin Hileman
>>> MyCategory::factory()->create()
PHP Error: Class 'MyCategory' not found in Psy Shell code on line 1
>>> Blog\MyCategory::factory()->create()
PHP Error: Class 'Blog\MyCategory' not found in Psy Shell code on line 1
>>> \Blog\MyCategory::factory()->create()
PHP Error: Class 'Blog\MyCategory' not found in Psy Shell code on line 1
>>> App\Models\Blog\MyCategory::factory()->create()
Illuminate\Database\QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'larablog.my_categories' doesn't exist (SQL: insert into `my_categories` (`updated_at`, `created_at`) values (2021-06-01 06:48:26, 2021-06-01 06:48:26))'
>>> \App\Models\Blog\MyCategory::factory()->create()
Illuminate\Database\QueryException with message 'SQLSTATE[42S02]: Base table or view not found: 1146 Table 'larablog.my_categories' doesn't exist (SQL: insert into `my_categories` (`updated_at`, `created_at`) values (2021-06-01 06:48:29, 2021-06-01 06:48:29))'
How to make such a structure work?
Sometimes it is necessary to clear the cache, this command worked in my project:
composer dump-autoload
Good luck!
use php artisan make:model ModelName -mcr -a
it will create all that you need. migration, seeder, factory, controller and model

Calling passport:client from route, "there are no commands defined in the "passport" namespace"

I have an issue where the passport namespace is not available when I call passport:client. I set up a brand new Laravel project with version 5.6.34 where I installed Laravel passport according to the documentation. I also checked a similar question and followed all steps there with no sucess.
Calling php artisan passport:client --password --name="Test" from the command line works without any issues and I can see the client in the database.
However if I create a route in routes/web.php like so:
<?php
use Illuminate\Support\Facades\Route;
use \Illuminate\Support\Facades\Artisan;
Route::get('/', function () {
Artisan::call('passport:client', [
'--password' => true,
'--name' => "Test client",
'--quiet' => true,
]);
});
and use the Artisan facade to call the command I get the error below when I navigate to http://homestead.test/.
Symfony \ Component \ Console \ Exception \ CommandNotFoundException
The command "passport:client" does not exist.
I have added Laravel\Passport\PassportServiceProvider::class in the providers array in config/app.php.
How can I call the passport:client command from a web route?
We have a Laravel application that has several hundred database connections which are handled dynamically. In the admin interface you can create a new project and thus a new database where we need to generate a client.
My other option is the instantiate a ClientRepository and call the createPasswordGrantClient() method but I would like to avoid this if possible. I am curious to know why the namespace is available when called on the CLI but not via a request. I can call other commands such as migrate:fresh via a request but passport:client will fail even if it is part of the migration or inside another command.
According to this link, I ran the below commands.
composer update
php artisan config:cache
php artisan migrate
php artisan passport:install
This helped me.

Base table or view not found: 1146 Table 'db.ken_permissions' doesn't exist

Sometimes, when I type :
php artisan
php artisan migrate
etc
I get the message:
[Illuminate\Database\QueryException]
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.ken_permissions' doesn't exist (SQL: select * from `ken_permissions`)
Debugging, I can tell my problem happens in the artisan file in:
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
I had already check this answer, and didn't work:
bootstrap/app.php is clean,
I don't have app/start folder ( L5.1),
routes.php is clean
php artisan -v or php artisan --pretend doesn't work, because artisan fails before running it seems.
The only thing I have is in app/Providers
public function boot(GateContract $gate)
{
parent::registerPolicies($gate);
// Dynamically register permissions with Laravel's Gate.
foreach ($this->getPermissions() as $permission) {
$gate->define($permission->name, function ($user) use ($permission) {
return $user->hasPermission($permission);
});
}
}
One solution is to delete all my tables, then composer dump-autoload, and then it work again, but it constantly comes back.
Is it a way to trace what migration is failing?
Any idea why is it happening?
Tx!
Go to the App\Provider\AuthServiceProvider
if you use on boot method GateContract ($this->getPermission() etc), remove or add to comment all after parent::registerPolicies($gate); and done run php artisan migrate
Adding to watcher's answer here
Remove any lines requesting data from your model from these files to be sure artisan is not trying to load data from your non-existent table:
bootstrap/start.php
app/start/global.php
app/start/local.php
app/routes.php
Also be sure to un-register any service providers that utilize data from that table in their register or boot methods inside of app/config/app.php.
You can move your migrations to a database/temp folder and run your migrations one by one
php artisan migrate --path=database/temp
you will know which migration is causing problem.
NOTE
Also you can use
php artisan migrate --pretend to get the query you are trying to do.

Laravel 5.1 refresh and seed a single table

I'm looking to refresh and seed a single table in Laravel 5.1. Is this even possible?
I have tried the below, but it gives an error (incorrect syntax).
php artisan migrate:refresh --path=database/migrations/CreateTableTimesheet
If I use: php artisan migrate:refresh it just says:
Nothing to migrate
You could use migrate:refresh command that will roll back all of your migrations and then execute the migrate command. This command effectively re-creates your entire database :
php artisan migrate:refresh
And you may use the --class option to specify a specific seeder class to run individually :
php artisan db:seed --class=UserTableSeeder
The full code will be :
php artisan migrate:refresh
php artisan db:seed --class=UserTableSeeder
Hope this helps.
Its better to truncate your same table first and then seed:-
public function run()
{
Table::truncate();
//seed your table here
}
then you can run your same seeder like this:-
php artisan db:seed --class=YourSeeder
Maybe first just backup the database, drop it and check if whole seeding, migrating and refreshing mechanic works. But first dump artisan autoload.
I don't think any answer so far addresses the question of migrating and seeding a single table. So, given the migration file database/migrations/create_foo_table.php and the seed file database/seeds/FooTableSeeder.php, which contains the FooTableSeeder seed class, you can do the following:
php artisan migrate:refresh --path=database/migrations/create_foo_table.php
php artisan db:seed --class=FooTableSeeder
This will rollback, migrate and seed your Foo table. See: rolling back migrations and running seeders in the Laravel 5.1 documentation (at the time of writing this, Laravel 7.x is out and the syntax has not changed).
php artisan tinker
>>> App\Status::truncate()
Will clear the statuses table
So you can do
>>> App\{MODEL_CLASS}::truncate()
I found this quite useful when I don't want to clear all the tables, especially users.
include full table name
example
php artisan migrate:refresh --path='database/migrations/2014_10_12_000000_create_table_timesheet.php'
You can do it in two steps:
Refresh your specific table:
php artisan migrate:refresh --path=database/migrations/00_create_foo_table.php
Seed tables set in database/seeds/DatabaseSeeder.php:
composer dump-autoload
php artisan db:seed
=== Extra information ===
You can comment the seeders you don't want to use in DatabaseSeeder.php:
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call([
FooSeeder::class,
// BarSeeder::class,
// UserSeeder::class,
]);
}
}
In this example, only database/seeds/FooSeeder.php will be passed.

Resources