Laravel逆引きTips – Model, Database

Laravel Laravel

Laravel逆引きTIps一覧へ戻る

モデルの基本的な使用

class User extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'email', 'password'];
}

// 使用例
$user = User::create([
    'name' => 'John Doe',
    'email' => 'john@example.com',
    'password' => bcrypt('password'),
]);
PHP

Eloquentリレーションシップ

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

// 使用例
$post = Post::find(1);
$user = $post->user;
$comments = $post->comments;
PHP

クエリビルダの活用

$users = User::where('active', 1)
             ->where('age', '>', 18)
             ->orderBy('name')
             ->limit(10)
             ->get();
PHP

マイグレーションの作成と実行

database/migrations/xxxx_xx_xx_create_posts_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->foreignId('user_id')->constrained();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
PHP

シーダーとファクトリの利用

database/seeders/UserSeeder.php
use Illuminate\Database\Seeder;

class UserSeeder extends Seeder
{
    public function run()
    {
        \App\Models\User::factory(10)->create();
    }
}
PHP
database/factories/UserFactory.php
use Illuminate\Database\Eloquent\Factories\Factory;

class UserFactory extends Factory
{
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'email' => $this->faker->unique()->safeEmail,
            'password' => bcrypt('password'),
        ];
    }
}
PHP

スコープとミューテータ

class User extends Model
{
    // ローカルスコープ
    public function scopeActive($query)
    {
        return $query->where('active', 1);
    }

    // グローバルスコープ
    protected static function booted()
    {
        static::addGlobalScope('ancient', function (Builder $builder) {
            $builder->where('created_at', '<', now()->subYears(2));
        });
    }

    // ミューテータ
    public function setNameAttribute($value)
    {
        $this->attributes['name'] = ucfirst($value);
    }
}

// スコープの使用
$activeUsers = User::active()->get();

// ミューテータの使用
$user->name = 'john'; // 'John'として保存される
PHP

テーブル内の全レコード取得

User::all();
PHP

Laravel逆引きTIps一覧へ戻る

Follow me!

コメント

PAGE TOP
タイトルとURLをコピーしました