**Laravel 12 API Development - Lecture 4: Controllers, Request Lifecycle & API Structure** --- # Lecture 4 ### โœ… Lecture Objective: By the end of this 3-hour lecture, trainees will: - Understand Laravel's request lifecycle clearly. - Learn how Laravel handles API requests from start to finish. - Create and organize API controllers using best practices. - Understand route grouping, prefixing, and route methods (GET, POST, etc.). --- ## โญ 1. Laravel Request Lifecycle (40 min) Welcome, everyone! Let's start today by understanding **how Laravel handles your request**. Imagine you open Postman and hit: ``` GET http://localhost:8000/api/v1/experts ``` ### Step-by-step Lifecycle: 1. The request enters the Laravel app through `public/index.php`, the **entry point** of all HTTP requests. 2. Laravel loads the **HTTP Kernel**, defined in `App\Http\Kernel.php`, which handles global and route middleware (like `auth`, `throttle`, etc.). 3. Laravel checks your request URL and method (GET, POST, etc.) and tries to find a matching route in `routes/api.php`. 4. If it finds the route, it calls the **corresponding controller method**, for example, `ExpertController@index`. 5. The controller might use a **Model** to fetch or store data, then returns a **response**. 6. Laravel sends back a **JSON response** (since it's API), often with a status code. > ๐Ÿง  Always remember: Laravel does a lot behind the scenes. Our job is to define **routes**, **controllers**, and **models** properly. --- ## ๐Ÿ“• 2. Laravel Routing Basics (50 min) Laravel handles routes in the `routes/api.php` file. This file is automatically created for every Laravel app. ### How to Create or View `api.php`: You don't need to generate it; it already exists. Check: ``` routes/api.php ``` Use this for **API-only routes**. ### Common Route Methods: ```php Route::get('/experts', [ExpertController::class, 'index']); Route::post('/experts', [ExpertController::class, 'store']); Route::put('/experts/{id}', [ExpertController::class, 'update']); Route::delete('/experts/{id}', [ExpertController::class, 'destroy']); Route::get('/experts/{id}', [ExpertController::class, 'show']); ``` Each one maps to a method inside a controller. These are called **HTTP verbs**, and they represent CRUD: - GET = Read - POST = Create - PUT = Update - DELETE = Delete ### Route Groups & Prefixing ```php Route::prefix('v1')->group(function () { Route::apiResource('experts', ExpertController::class); }); ``` ### apiResource - Full CRUD Generator ```php Route::apiResource('experts', ExpertController::class); ``` Laravel automatically assumes controller method names like `index`, `store`, `show`, etc. --- ## ๐Ÿ“„ 3. Creating API Controllers (25 min) ### Basic Controller ```bash php artisan make:controller Api/ExpertController ``` ### Resource Controller ```bash php artisan make:controller Api/ExpertController -r ``` Includes: - index(), store(), show(), update(), destroy() > โœ๏ธ Use `-r` for full CRUD structure with REST APIs. --- ## ๐Ÿ“ 4. Form Request Validation (30 min) ### Create Request ```bash php artisan make:request StoreExpertRequest ``` ### Example Rules: ```php public function rules(): array { return [ 'name' => 'required|string|max:100', 'bio' => 'nullable|string|max:500', 'industry' => 'required|string|max:100', 'category' => 'nullable|string', 'experience_years' => 'nullable|integer|min:0', ]; } ``` Used inside controller like this: ```php public function store(StoreExpertRequest $request) { $validated = $request->validated(); $expert = Expert::create($validated); return response()->json($expert, 201); } ``` --- ## ๐Ÿ“‚ 5. Creating & Understanding Models (Users First) (45 min) ### Create User Model and Migration: ```bash php artisan make:model User -m ``` Edit the migration: ```php $table->string('name'); $table->string('email')->unique(); $table->string('password'); $table->timestamps(); ``` Then: ```bash php artisan migrate ``` This creates `users` table in `database/database.sqlite` ### Use DB Browser for SQLite - Download "DB Browser for SQLite" - Open the file: `database/database.sqlite` - Browse tables, insert/edit rows, run queries ### Create Expert Model after User: ```bash php artisan make:model Expert -m ``` Migration should include: ```php $table->string('name'); $table->text('bio')->nullable(); $table->string('industry'); $table->foreignId('user_id')->constrained('users'); ``` Run: ```bash php artisan migrate ``` > โš ๏ธ Migrations must be done in order: User first, Expert second. --- ## ๐Ÿ“ˆ 6. Implementing CRUD - First with Dummy Data, Then DB (40 min) ### Phase 1: Dummy Data ```php public function index() { return response()->json([ ['id' => 1, 'name' => 'Dr. Lina'], ['id' => 2, 'name' => 'Mr. Karim'] ]); } ``` ### Phase 2: With DB ```php public function index() { return response()->json(Expert::all()); } ``` The same for: - `store()` with `Expert::create()` - `show()` with `Expert::findOrFail()` - `update()` with `$expert->update()` - `destroy()` with `$expert->delete()` > ๐Ÿงช Test both phases to see the difference between static and dynamic APIs. --- ## ๐Ÿ›  Project Tip: Model Implementation Order (10 min) Recommended order to prevent FK issues: 1. `User` - base model 2. `Expert` - linked to user 3. `Booking` - links both 4. Later: Reviews, Messages, Ratings, etc. --- ## ๐Ÿ“ƒ Assignment 1. Create User & Expert models + migrations 2. Migrate both tables in SQLite 3. Create `ExpertController` with CRUD 4. Start with dummy data, then switch to DB 5. Use FormRequest for validation 6. Browse SQLite with DB Browser 7. Test all endpoints with Postman --- ## Resources ### API design text file ``` Get List of users endpoint http://DomainNameOrIP.com/ BASE URL Resource ENDPOINT + HTTP VERB prefix: /api /users/get FULL API ENDPOINT: http://DomainNameOrIP.com/PREFIX/users/get GET http://DomainNameOrIP.com/api/users/get GET USers is RESOURCE Response is list of users as JSON format --------------- Create new user ENDPOINT (Specification)---------- Resource: users/add POST name email userId Body: { "name":"", "email":"", "userId":"" } <=> [ 'name'=>'', 'email'=>'', 'userId'=>'' ] in controller of create user, extract inputs from the http request body response should be http status code 200 --------------------------------------------------- - Produce api.php file in routes directory - Create endpoint to get list of experts with below fields: fullName industry age country - Create endpoint to create new expert in the system : fullName : mandatory, minimum length is 3 and max is 15 industry: programming, payment, engineering age: 18 - 125 country: iraq, UAE, jordan response is json CRUD: Create, READ, Update, Delete /api/users GET (get all) /api/users POST (store new user) /api/users/{ID} PATCH/PUT (update already exists user) /api/users/{ID} DELETE ``` End of Lecture 4 ## Git and Github Case 1: if you have to initialize git repo by your self and push it into the github first, go to Github and create new repo then ``` git init git add * git commit -m 'your message' git branch -M main git remote add origin GITHUB_URL git push -u origin main ``` case 2: in case you want to clone a remote repo into your machine ``` ```