Tartalomjegyzék

< Leaf

Leaf modell

Modell létrehozása

php leaf g:model Employee
app/models/Employee.php
<?php
 
namespace App\Models;
 
class Employee extends Model
{
    // 
}

Modell és tábla összekapcsolása

Az Employee modellt hozzákötjük a táblához.

app/models/Employee.php
<?php
 
namespace App\Models;
 
class Employee extends Model
{
    protected $table = 'employees';
}

A működéshez szükség van az adatbázis modul telepítésére:

leaf install db

A modell használata a kontrollerben

app/controllers/EmployeesController.php
use App\Models\Employee;
//...
 
    public function index()
    {
        $employees = Employee::all();
        response()->json([
            'employees' => $employees
        ]);
    }

Ellenőrzés

http localhost:5500/employees

A modell használata create műveletre

app/controllers/EmployeesController.php
//...
use App\Models\Employee;
//...
 
    public function store() {
 
        $employee = new Employee;
        $employee->name = request()->get('name');
        $employee->city = request()->get('city');
        $employee->salary = request()->get('salary');
        $res = $employee->save();
 
        response()->json([
            'success' => $res
        ]);
    }

A modell használata update műveletre

app/controllers/EmployeesController.php
//...
use App\Models\Employee;
//...
    public function update($id) {
        $employee = Employee::find($id);
        $employee->name = request()->get('name');
        $employee->city = request()->get('city');
        $employee->salary = request()->get('salary');
        $res = $employee->save();
 
        response()->json([
            'success' => $res
        ]);        
    }

A modell használata Delete műveletre

app/controllers/EmployeesController.php
//...
use App\Models\Employee;
//...
    public function delete($id) {
        $employee = Employee::find($id);
        $res = $employee->delete();
 
        response()->json([
            'success' => $res
        ]);        
    }