Connecting With the Database Using Migration (1)
Connecting With the Database Using Migration (1)
In the terminal, run the following command to generate a migration file for creating a users table
If migration is successful, you can see a file created in this following directory:
database\migrations\0001_01_01_000000_create_users_table.php
2. Edit the Migration File:
(i) Navigate to the generated migration file in database/migrations/ and open it.
(ii) Add the following code inside the up() method to define the structure of the users table:
Open routes/web.php and add the following route to test if Laravel is properly connected to the
database:
use Illuminate\Support\Facades\DB;
Route::get('/test-database', function () {
// Fetch data from the 'users' table
$users = DB::select('SELECT * FROM users');
return $users; // Show the users data (empty array if no data)
});
(ii) If your database is connected properly, it will return an empty array ([]) or any data in the
users table if you have added users.
Extras:
To undo all migration, use the following command:
If you want to reset your database and re-run all migrations (warning: this will delete all data in
your database), you can use the migrate:fresh command.
This command will drop all existing tables and re-run all migrations from scratch.