class Laravel Model Controller extends Post
@created_at(
"2025-10-09 07:43"
)
@tag(
"Laravel"
)
@tag(
"Model"
)
@tag(
"Controller"
)
## 🧩 Model Dosyaları
### `app/Models/Department.php`
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Department extends Model
{
use HasFactory;
protected $fillable = ['name'];
// Bir departmanın birçok kullanıcısı olabilir
public function users()
{
return $this->hasMany(User::class);
}
}
---
### `app/Models/User.php`
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class User extends Model
{
use HasFactory;
protected $fillable = ['name', 'email', 'department_id'];
// Kullanıcı bir departmana aittir
public function department()
{
return $this->belongsTo(Department::class);
}
}
---
## ⚙️ Controller
### `app/Http/Controllers/DepartmentController.php`
namespace App\Http\Controllers;
use App\Models\Department;
use Illuminate\Http\Request;
class DepartmentController extends Controller
{
// Tüm departmanları listele
public function index()
{
$departments = Department::with('users')->get();
return response()->json($departments);
}
// Yeni departman oluştur
public function store(Request $request)
{
$validated = $request->validate([
'name' => 'required|string|max:100',
]);
$department = Department::create($validated);
return response()->json($department, 201);
}
// Belirli bir departmanı göster
public function show($id)
{
// 👇 Burada findOrFail kullanıyoruz
$department = Department::with('users')->findOrFail($id);
return response()->json($department);
}
// Departmanı sil
public function destroy($id)
{
$department = Department::findOrFail($id);
$department->delete();
return response()->json(['message' => 'Departman silindi.']);
}
}
---
## 🛣️ Route Tanımı
`routes/api.php`
use App\Http\Controllers\DepartmentController;
Route::apiResource('departments', DepartmentController::class);
---
## 🧠 Kısa Özet
| Metot | Açıklama |
| --------------- | ---------------------------------------- |
| `find()` | ID ile arar, **bulamazsa null döner.** |
| `findOrFail()` | ID ile arar, **bulamazsa 404 fırlatır.** |
| `with('users')` | İlişkili kullanıcıları eager load eder. |
---
💬 **Gerçek kullanım örneği:**
GET /api/departments/5
Eğer `id = 5` yoksa:
{
"message": "No query results for model [App\\Models\\Department] 5"
}
ve `HTTP 404` döner.
---