카테고리 없음

Laravel 06. Eloquent ORM

테디아저씨 2026. 4. 24. 11:11

 

 

 

 

Eloquent ( 읽기 쉬운 )

ORM (Object Relational Mapping)

 

 

라라벨은 데이터를 객체로 만들어 다루게 해줍니다.

 

기존 PHP 에서 다음과 같은 sql 문으로 데이터를 가져옵니다.

SELECT * FROM trucks;

 

 

Model

테이블 Model
행(row) 객체
컬럼 속성

 

 

 

 

라라벨에서는

Post::all();

 

모델생성

php artisan make:model TruckKind

 

대문자로 시작하고, 두개 단어를 쓸때는 각각 대문자를 써주면 _ 로 구분된 테이블이 생성됩니다.

 

 

생성된 위치는

app/Models/TruckKind.php

 

기본구조

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class TruckKind extends Model
{
    //


}

 

 

보통은 migration 파일을 함께 생성하여 사용합니다.  

** 삭제하고 다시 만들어보겠습니다.

php artisan make:model TruckKind -m

 

 

migration 파일을 확인합니다.

   INFO  Model [app/Models/TruckKind.php] created successfully.  

   INFO  Migration [database/migrations/2026_04_24_023239_create_truck_kinds_table.php] created successfully.

 

 

migration 수정하여 테이블 설계

 

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('truck_kinds', function (Blueprint $table) {
            $table->id();
            $table->string('name',30)->comment("trunk kind name");
            $table->integer('seq')->default(0)->comment("sequence");
            $table->string('description')->nullable()->comment("description");
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('truck_kinds');
    }
};

 

php artisan migrate

 

 

CRUD 기본

$truck = new TruckKind();
$truct->name = 'Pickup truck';
$truct->seq = 1;
$truct->description = 'A pickup truck is a type of light-duty truck that combines the comfort of a passenger car with the cargo capacity of a truck. It features a cabin for the driver at the front and an open cargo area, known as a truck bed, at the rear.';
$truct->save();   // or $truct->add();


TruckKind::create([
    'name' => 'Tank truck',
    'seq' => 2,
    'description' => 'A pickup truck is a type of light-duty truck that combines the comfort of a passenger car with the cargo capacity of a truck. It features a cabin for the driver at the front and an open cargo area, known as a truck bed, at the rear.'
]);


// error  fillable


DB::table('truck_kinds')->insert(['name'=>'Box truck', 'seq'=>3, description=>'']);

 

 

 

create는 fillable 설정이 필요합니다.

 

화이트리스트

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class TruckKind extends Model
{
    //

    protected $fillable = ['name', 'seq', 'description'];
   
}

 

보안을 위해 허용된 컬럼만 입력할 수 있게 합니다.

 

블랙리스트

// User Model

protected $guarded = ['id', 'is_admin'];

 

 

 

$user->save(); / $user->add();  //  보호 받지 않고 저장이 됩니다.

 

 

Create  와  insert

요약 및 차이점 비교
방식 Eloquent (모델) :: create() Query Builder (DB) :: insert()  Eloquent (관계) :: save() (add)
속도 보통 매우 빠름 보통
타임스탬프 자동 설정 수동 설정 필요 자동 설정
모델 이벤트 트리거됨 작동 안 함 트리거됨
대량 할당 fillable 보호 보호 안 됨 해당 없음

 

Update

$truck_kind = TruckKind::find(1);
$truck_kind->name = "Dump truck";
$truck_kind->save();
//$truck_kind->update();

or 

TruckKind::where('id', 1)->update([
    'name' => 'Dump truck 2'
]);

 

 

Delete

$truck_kind = TruckKind::find(1);
$truck_kind->delete();

or 

TruckKind::destroy(1);

 

 

Relationships

make truck

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('trucks', function (Blueprint $table) {
            $table->id();
            $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
            $table->foreignId('truck_kind_id')->constrained('truck_kinds')->onDelete('cascade');
            $table->string('name',30)->comment("truck my name");
            $table->timestamps();
            
            // ->constrained('users')  관계를 설정
            // ->constrained()  자동설정
            // ->onDelete('cascade'); 삭제시 지동삭제
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('trucks');
    }
};

 

 

 

1:N 관계

 

// User Model

public function trucks()
{
    return $this->hasMany(Truck::class);
}
// controller

$user = User::find(1);
$user->trucks; // 내가 등록한 목록

 

 

// Truck Model

public function user()
{
    return $this->belongsTo(User::class);
}
// controller

$post = Truck::find(1);
$post->user; // 작성자

 

 

1:1 관계

 

User <-> Profile

//User Model 


public function profile()
{
    return $this->hasOne(Profile::class);
}

 

// Profile Model

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

 

 

With 를 이용하여 속성(프로퍼티)으로 사용하기

$trucks = Truck::with('user')->get();

 

 

 

과제.

User 객체를 선언하고 해당 사용자가 가진 트럭 목록을 만들어주세요.

( 아직 로그인을 공부하지 않았기 때문에 임의의 유저로 )

 

Quiz. 

컨트롤러에 public function 이 의미하는 것과 

public 외에 다른것을 사용할 수 있다면 그 차이는 무엇인가요?