In this section we will see how to use dateTime function & migration in laravel 9. We will create user birthday filed using dateTime().
Step 1: Create Laravel Project
Installing a fresh new laravel application, so head over to the terminal, type the command, and create a new laravel app.
composer create-project --prefer-dist laravel/laravel laravel-datetime
Step 2: Connect Database
Now, you have to connect the laravel app to the database, hence open the .env configuration file and add the database credentials as suggested below.
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password
Step 3: Install Laravel Breeze
Next, you need install laravel breeze via composer.
composer require laravel/breeze --dev
Authentication to run below command.
php artisan breeze:install
npm install
npm run dev
php artisan migrate
Step 4: Add dateTime filed in User Migration , Model and Controller
migrations/2014_10_12_000000_create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->dateTime('birth_day')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
Add in User Model dateTime filed.
app/Models/User.php
protected $fillable = [
'name',
'email',
'password',
'birth_day'
];
Add birth_day in user.
app/Http/Controllers/Auth/RegisteredUserController.php
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
'birth_day' => $request->birth_day,
]);
Step 5: Add local datetime in Blade View
views/auth/register.blade.php
<x-text-input id="birth_day" class="block w-full mt-1"
type="datetime-local"
name="birth_day" required />
Step 6: Check dateTime filed via laravel tinker
Run the tinker in terminal.
php artisan ti
Psy Shell v0.11.8 (PHP 8.1.3 — cli) by Justin Hileman
>>> App\Models\User::all()
=> Illuminate\Database\Eloquent\Collection {#4377
all: [
App\Models\User {#4336
id: 1,
name: "Forrest Foster",
email: "[email protected]",
email_verified_at: null,
#password: "$2y$10$ZGRn9PpDSZUd8uokEvLR.uiFimc6wFw4.jnzj3qbsBs0.SY.46foi",
birth_day: "1988-07-06 13:55:00",
#remember_token: null,
created_at: "2022-09-25 17:32:22",
updated_at: "2022-09-25 17:32:22",
},
],
}