0% found this document useful (0 votes)
2 views

fes 2024

The document outlines the theoretical and practical components of a Laravel project, including the creation of models, migrations, and controllers for managing students and courses. It details the steps for setting up the project, implementing CRUD operations, and creating views using Blade templates. Additionally, it covers validation, middleware, and job handling for sending emails upon user registration.

Uploaded by

Maryam El Mribet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

fes 2024

The document outlines the theoretical and practical components of a Laravel project, including the creation of models, migrations, and controllers for managing students and courses. It details the steps for setting up the project, implementing CRUD operations, and creating views using Blade templates. Additionally, it covers validation, middleware, and job handling for sending emails upon user registration.

Uploaded by

Maryam El Mribet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Correction

Partie théorique : QCM

Question 1 : a

Question 2 : a

Question 3 : a, b

Question 4 : a

Question 5 : d

Partie pratique

1. Création du projet Laravel

composer create-project laravel/laravel Contoso_university

2. Compilation des ressources avec Vite

La procédure est :

* Installer les dépendances avec `npm install`

* Lancer `npm run dev` dans le développement ou `npm run build` pour la production

3. Création des modèles et migrations

php artisan make:model Student -m

php artisan make:model Course –m

php artisan make:migration create_enrollments_table

4. Modification des migrations

pour la table students:

Schema::create('students', function (Blueprint $table) {

$table->id();

$table->string('last_name');

$table->string('first_mid_name');

$table->dateTime(enrollment_date);
});

Pour la table courses :

Schema::create(‘courses’, function (Blueprint $table) {

$table->id();

$table->string(‘title’);

$table->string(‘credits’);

});

Pour la table enrollments(table pivot) il va devenir course_student dans le convention de nommage

Dans laravel:

Schema::create('course_student', function (Blueprint $table) {

$table->id();

$table->foreignId('student_id')->constrained();

$table->foreignId('course_id')->constrained();

$table->double('grade')->nullable();

});

Commande pour exécuter les migrations :

php artisan migrate

5. Génération des données avec Faker

Créer les factories :

php artisan make:factory Student --model=Student

php artisan make:factory Course --model=Course

class StudentFactory extends Factory {

public function definition() {

return [

'last_name' => faker()->lastName(),

'first_mid_name' => faker()->firstName(),

'enrollment_date' => $this->faker->dateTime(),


];

}}

class CourseFactory extends Factory {

public function definition() {

return [

'title' => faker()->sentence(),

'credits' => faker()->text()

];

}}

Créer les seeders :

php artisan make:seeder StudentSeeder

public function run(){

Student::factory(20)->create();

php artisan make:seeder CourseSeeder

public function run(){

Course::factory(20)->create();

La commande pérmettant la génération des données à partir les seeders

php artisan db:seed

6. Modification des modèles

Student.php :

class Student extends Model

protected $fillable = [‘last_name’, ‘first_mid_name’, ‘enrollment_date’];

public function courses()


{

return $this->belongsToMany(Course::class)->withPivot(‘grade’);

Course.php :

class Student extends Model

protected $fillable = [‘title’,’credits’];

public function students()

return $this->belongsToMany(Student::class)->withPivot(‘grade’);

7. Création du contrôleur et définition des routes

php artisan make:controller StudentController –resource

Dans routes/web.php :

Route::resource('students', StudentController::class);

Route::get('/students/delete/{studentID}', [StudentController::class, 'delete'])-


>name('students.delete');

8. Actions CRUD dans StudentController

public function index()

$students = Student::paginate(3);

return view('students.index', compact('students'));

public function details($id)

{
$student = Student::find($id);

return view('students.show', compact('student'));

public function create()

return view('students.create');

public function store(Request $request)

Student::create($request->all());

return redirect()->route('students.index');

public function edit($id)

$student = Student::find($id);

return view('students.edit', compact('student'));

public function update(Request $request, $id)

$student = Student::find($id);

$student->update($request->all());

return redirect()->route('students.index');

public function destroy($id)

$student = Student::find($id);
$student->delete();

return redirect()->route('students.index');

9. Fichiers Blade

students.index :
@extends('layouts.app')

@section('content')

<div>

<h2>Students</h2>

<a href="{{ route('students.create') }}">Create New</a>

<form method=”GET” action = “{{route(‘students.index’)}}”>

<label>Find by name: </label>

<input type=”text” name=”search” />

<button type=”submit”>Search</button>

<table>

<thead>

<tr>

<th> </th>

<th>Last Name</th>

<th>First Name</th>

<th>Enrollment Date</th>

</tr>

</thead>

<tbody>

@foreach($students as $student)

<tr>

<td>

<a href="{{ route('students.edit', $student->id) }}">Edit</a>

<a href="{{ route('students.show', $student->id) }}">Details</a>

<form action="{{ route('students.destroy', $student->id) }}" method="POST">


@csrf

@method('DELETE')

<button type="submit">Delete</button>

</form>

</td>

<td>{{ $student->last_name }}</td>

<td>{{ $student->first_mid_name }}</td>

<td>{{ $student->enrollment_date->format(‘d/m/Y’) }}</td>

</tr>

@endforeach

</tbody>

</table>

{{$students->links()}}

</div>

@endsection

students.show :
@extends('layouts.app')

@section('content')

<div>

<h1> Details</h1>

<p>Last Name: {{ $student->last_name }}</p>

<p>First Name: {{ $student->first_mid_name }}</p>

<p>Enrollment Date: {{ $student->enrollment_date->format('d/m/Y H:i:s') }}</p>

<table>

<thead>

<tr>

<th>Course Title</th>

<th>Grade</th>

</tr>

@foreach($student->courses as $course)
<tr>

<td>{{ $course->title }}</td>

<td>{{ $course->pivot->grade }}</td>

</tr>

@endforeach

</table>

<a href="{{ route('students.index') }}">Back to List</a>

@endsection

students.create :
@extends('layouts.app')

@section('content')

<h1>Create</h1>

<form method="POST" action="{{ route('students.store') }}">

@csrf

<label>Last Name</label>

<input type="text" name="last_name" />

@error('last_name') <span>{{ $message }}</span> @enderror

<label>First Name</label>

<input type="text" name="first_mid_name" />

@error('first_mid_name') <span>{{ $message }}</span> @enderror

<label>Enrollment Date</label>

<input type="datetime" name="enrollment_date" />

@error('enrollment_date') <span>{{ $message }}</span> @enderror

<button type="submit">Create</button>

</form>

<a href="{{ route('students.index') }}">Back to List</a>

@endsection

students.edit :
@extends('layouts.app')

@section('content')

<h1>Edit</h1>
<form method="POST" action="{{ route('students.update', $student->id) }}">

@csrf

@method(‘put’)

<label>Last Name</label>

<input type="text" name="last_name" value="{{ $student->last_name }}">

@error('last_name') <span>{{ $message }}</span> @enderror

<label>First Name</label>

<input type="text" name="first_mid_name" value="{{ $student->first_mid_name }}">

@error('first_mid_name') <span>{{ $message }}</span> @enderror

<label>Enrollment Date</label>

<input type="text" name="enrollment_date" value="{{ $student->enrollment_date-


>format('d/m/Y H:i:s') }}">

@error('enrollment_date') <span>{{ $message }}</span> @enderror

<button type="submit">Save</button>

</form>

<a href="{{ route('students.index') }}">Back to List</a>

@endsection

10. Création de requête de formulaire

php artisan make:request StoreStudentRequest

php artisan make:request UpdateStudentRequest

11. Règles de validation

Dans StoreStudentRequest.php :

public function rules()

return [

‘last_name’ => 'required|string|max:50',

'first_mid_name' => 'required|string|max:50',

'enrollment_date' => 'required|date_format:d/m/Y H:i:s'

];
}

12.vue d’inscription

@extends('layouts.app')

@section('content')

<h1>Register</h1>

<form method="POST" action="{{ route('register') }}">

@csrf

<label>Nom</label>

<input type="text" name="nom"/>

<label>Email</label>

<input type="email" name="email"/>

<label>Password</label>

<input type="password" name="password”/>

<button type="submit">s’inscrire</button>

</form>

@endsection

13. Pour l'authentification :

@extends('layouts.app')

@section('content')

<h1>Login</h1>

<form method="POST" action="{{ route('login') }}">

@csrf

<label>Email</label>

<input type="email" name="email" >

<label>Password</label>

<input type="password" name="password">

<button type="submit">se connecter</button>

</form>

@endsection

14. Tests unitaires :

php artisan make:test StudentControllerTest


class StudentControllerTest extends TestCase

use RefreshDatabase;

public function test_create_student()

$user = User::factory()->create(['role' => 'admin']);

$response = $this->actingAs($user)->post(route('students.store'), [

'last_name' => 'Doe',

'first_mid_name' => 'John',

'enrollment_date' => '01/01/2023 12:00:00',

]);

$response->assertRedirect(route('students.index'));

$this->assertDatabaseHas('students', ['last_name' => 'Doe']);

public function test_search_student_by_name()

$user = User::factory()->create();

Student::factory()->create(['last_name' => 'Doe']);

$response = $this->actingAs($user)->get(route('students.index', ['search' => 'Doe']));

$response->assertStatus(200);

$response->assertSee('Doe');

public function test_update_student()

$user = User::factory()->create(['role' => 'admin']);

$student = Student::factory()->create();
$response = $this->actingAs($user)->put(route('students.update', $student->id), [

'last_name' => 'nouvelle nom',

'first_mid_name' => 'nouvelle prènom',

'enrollment_date' => '01/01/2023 12:00:00',

]);

$response->assertRedirect(route('students.index'));

$this->assertDatabaseHas('students', ['last_name' => 'nouvelle nom']);

public function test_delete_student()

$user = User::factory()->create(['role' => 'admin']);

$student = Student::factory()->create();

$response = $this->actingAs($user)->delete(route('students.destroy', $student->id));

$response->assertRedirect(route('students.index'));

$this->assertDatabaseMissing('students', ['id' => $student->id]);

15. Middlewares :

Commande pour céer un middleware : php artisan make :middleware RoleMiddleware

class RoleMiddleware

public function handle(Request $request, Closure $next, $role)

if (auth()->user()->role !== $role) {

abort(403, 'Unauthorized');

}
return $next($request);

Enregistrer le middleware dans app/Http/Kernel.php:

protected $routeMiddleware = [

'role' => \App\Http\Middleware\RoleMiddleware::class,

];

Route::middleware(['auth'])->group(function () {

Route::get('/students/search', [StudentController::class, 'search'])->name('students.search');

Route::middleware(['role:admin'])->group(function () {

Route::post('/students', [StudentController::class, 'store']);

Route::put('/students/{student}', [StudentController::class, 'update']);

Route::delete('/students/{student}', [StudentController::class, 'destroy']);

});

});

16. Création d'un composant :

php artisan make:component Header

class Header extends Component

public function render()

return view('components.header');

Header.blade.php

<header>

<nav>

<a href="{{ url('/') }}">Home</a>

<a href="{{ route('students.index') }}">Students</a>

<a href="{{ route('courses.index') }}">Courses</a>

</nav>
</header>

17. Job et mail :

php artisan make:job EnvoyerEmailAdmin

php artisan make:mail UserRegistered

class EnvoyerEmailAdmin implements ShouldQueue

use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

protected $user;

public function __construct($user)

$this->user = $user;

public function handle()

Mail::to('[email protected]')->send(new \App\Mail\UserRegistered($this->user));

class UserRegistered extends Mailable

use Queueable, SerializesModels;

public $user;

public function __construct($user)

$this->user = $user;

public function build()

return $this->subject('nouvelle utilisateur inscrit')

->view('emails.user_registered');
}

Migration pour les jobs :

php artisan queue:table

php artisan migrate

You might also like