上一篇講了在 Laravel 存取資料庫的方法,不過並不是很建議大家這麼做,一般我們都是透過 model 來操作資料庫會比較好,所以我們如果要建立 Laravel 的 Model 的話,可以先執行以下的指令:
php artisan make:model Flight
這時候就會在 app/Models 裡面建立一個 Flight 的 Model:
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
use HasFactory;
}
因為是要操作資料庫,也可以寫這樣,同時 migration 新的資料表:
php artisan make:model Flight -m
簡單建立一個資料表:
Schema::create('flights', function (Blueprint $table) {
$table->id();
$table->string("code");
$table->string("name");
$table->timestamps();
});
跑 migrate:
php artisan migrate
這樣我們就可以建立好資料表了。
接著建立一個 controller 來存取 model:
php artisan make:controller FlightController
接著來輸入資料:
use App\Models\Flight;
public function add(){
$flight = new Flight;
$flight->name = "test";
$flight->code = "123";
$flight->save();
}
也可以用表單的方法輸入,先在 Flight 的 Model 這樣設定:
class Flight extends Model
{
use HasFactory;
protected $fillable = [
'name',
'code'
];
}
因為要用 create 輸入,所以要把欄位設定為 fillable。
接著透過表單把資料寫入資料庫的方法:
public function add(Request $request){
$data = $request->only([
'name',
'code'
]);
Flight::create($data);
}
這樣就可以把資料輸入了,有資料後我們再把資料讀出來。
$flights = Flight::get();
return view('flight', [
'flights'=>$flights
]);
讀取資料:
@foreach($flights as $key => $flight)
<li>{{$flight->name}}</li>
@endforeach
修改的方法:
$flight = Flight::find(1); $flight->name = 'Paris to London'; $flight->save();
或是:
Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);
Laravel 的 model 其實很聰明,也可以用這種方法來判斷要輸入新資料或修改。
$data = $request->only([
'id',
'name',
'code',
]);
Flight::updateOrInsert(['id'=>$data['id']],$data);
delete 資料也很方便:
Flight::destroy($id);
laravel 有一個 softDeletes 的設定,可以不讓資料真的被刪掉,但需要在 migration 的時候加上這段:
$table->softDeletes();
接著在 model 加上這段:
class Flight extends Model
{
use HasFactory;
use SoftDeletes;
protected $fillable = [
'name',
'code'
];
}
這樣刪除資料就不會真的把資料刪掉了,以上是 model 的基本用法。