カラムの追加
以下のコマンドを実行してデータベースの雛形を作る。
php artisan migrate
以下のファイルを開きupメソッド内に追加したいカラムを追加する。
vim database/migrations/2014_10_12_000000_create_users_table.php
useridを追加した。
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('userid');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
再び以下のコマンドを実行すると実際のデータベースにカラムが追加される。
php artisan migrate
Eloquentの使用
Eloquentを使用するとデータベースの追加や取得がSQL文を書かなくても簡単に操作できるようになる。
Userモデルを作成
php artisan make:model User
app/Models/User.phpが作成される。
User.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasFactory;
}
実際にControllerでデータベースusersに追加するためのControllerを以下のようにする。
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
{
//
public function index(){
$user = new User();
$user->userid = 'testid';
$user->name = 'test';
$user->email = 'test@test';
$user->password = 'password';
$user->save();
}
}
以上で基本的な追加は可能になります。
コメント