finished api

This commit is contained in:
Clément
2025-06-04 19:50:52 +02:00
parent 1551f6226e
commit f488f7e01d
32 changed files with 1078 additions and 30 deletions

View File

@@ -0,0 +1,69 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Billet;
use App\Http\Resources\BilletResource;
use App\Http\Resources\BilletsResource;
use Illuminate\Support\Facades\Log;
class BilletController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
try {
// Le résultat de la requête est retourné directement en JSON.
// return Billet::all();
return BilletsResource::collection(Billet::all());
} catch (\Illuminate\Database\QueryException $e) {
Log::channel('projectLog')->error('Erreur accès base de données');
return response()->json([
'message' => 'Ressource indisponible.',
], 500);
}
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*/
public function show($id) {
try {
return new BilletResource(Billet::with('commentaires', 'commentaires.user')->findOrFail($id));
}
catch (\Illuminate\Database\QueryException $e) {
Log::error('Erreur accès base de données');
return response()->json([
'message' => 'Ressource indisponible.',
], 500);
}
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}

View File

@@ -0,0 +1,59 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreCommentairesRequest;
use Illuminate\Http\Request;
use App\Models\Commentaire;
use Illuminate\Support\Facades\Log;
class CommentaireController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(StoreCommentairesRequest $request)
{
try {
$commentaire = Commentaire::create($request->validated());
return response()->json($commentaire, 201);
} catch (\Illuminate\Database\QueryException $e) {
Log::channel('projectError')->error('Erreur accès base de données');
return response()->json([
'message' => $e->getMessage(),
], 500);
}
}
/**
* Display the specified resource.
*/
public function show(string $id)
{
//
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Http\Controllers;
use App\Http\Resources\UserResource;
use Illuminate\Http\Request;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
//
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
// Validate the request data
$validatedData = $request->validate([
'name' => 'required|string|max:50',
'email' => 'required|email|max:50|unique:users',
'password' => 'required|string|min:8|',
]);
// Create a new user
$user = \App\Models\User::create([
'name' => $validatedData['name'],
'email' => $validatedData['email'],
'password' => bcrypt($validatedData['password']),
]);
$token = $user->createToken('auth_token')->plainTextToken;
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
], 201);
}
/**
* Display the specified resource.
*/
public function show(Request $request)
{
return new UserResource($request->user());
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, string $id)
{
//
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
//
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StoreBilletRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
//
];
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\Rule;
class StoreCommentairesRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'COM_DATE' => ['required', 'date'],
'COM_CONTENU' => ['required', 'string', 'max:200'],
'billet_id' => ['required', 'integer'],
'user_id' => ['required', 'integer', Rule::exists('users', 'id')->where(function ($query) {
$query->where('id', $this->user()->id);
})],
];
}
public function failedValidation(\Illuminate\Contracts\Validation\Validator $validator) {
throw new HttpResponseException(
response()->json([
'success' => false,
'message' => 'Validation failed',
'data' => $validator->errors(),
], 422)
);
}
public function validated($key = null, $default = null)
{
return parent::validated($key, $default);
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateBilletRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
//
];
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdateCommentairesRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return false;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
//
];
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class BilletResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'Date' => $this->BIL_DATE,
'Titre' => $this->BIL_TITRE,
'Contenu' => $this->BIL_CONTENU,
'Commentaires' => CommentaireResource::collection($this->whenLoaded('commentaires')),
];
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class BilletsResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'Date' => $this->BIL_DATE,
'Titre' => $this->BIL_TITRE,
'Contenu' => $this->BIL_CONTENU,
];
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class CommentaireResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'Date' => $this->COM_DATE,
'Auteur' => $this->user->name,
'Contenu' => $this->COM_CONTENU,
];
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace App\Http\Resources;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public static $wrap = 'user';
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->getKey(),
'nom' => $this->name,
'email' => $this->email,
];
}
}

View File

@@ -0,0 +1,31 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Billet extends Model
{
/** @use HasFactory<\Database\Factories\BilletFactory> */
use HasFactory;
protected $fillable = [
'BIL_DATE',
'BIL_TITRE',
'BIL_CONTENU',
];
protected $hidden = [
'id',
'created_at',
'updated_at',
];
// Un billet a plusieurs commentaires.
// Cette fonction sera utile pour afficher les commentaires d'un billet sélectionné.
public function commentaires()
{
return $this->hasMany(Commentaire::class);
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* Created by Reliese Model.
*/
namespace App\Models;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
/**
* Class Commentaire
*
* @property int $id
* @property Carbon $COM_DATE
* @property string $COM_AUTEUR
* @property string $COM_CONTENU
* @property int $billet_id
* @property Carbon|null $created_at
* @property Carbon|null $updated_at
*
* @property Billet $billet
*
* @package App\Models
*/
class Commentaire extends Model
{
protected $table = 'commentaires';
protected $casts = [
'COM_DATE' => 'datetime',
'billet_id' => 'int'
];
protected $fillable = [
'COM_DATE',
'COM_AUTEUR',
'COM_CONTENU',
'billet_id',
'user_id'
];
protected $hidden = [
'id',
'created_at',
'updated_at',
'billet_id'
];
public function billet()
{
return $this->belongsTo(Billet::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}

View File

@@ -6,11 +6,12 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
/** @use HasFactory<\Database\Factories\UserFactory> */
use HasFactory, Notifiable;
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Policies;
use App\Models\Billet;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class BilletPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return false;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Billet $billet): bool
{
return false;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return false;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Billet $billet): bool
{
return false;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Billet $billet): bool
{
return false;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, Billet $billet): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, Billet $billet): bool
{
return false;
}
}

View File

@@ -0,0 +1,66 @@
<?php
namespace App\Policies;
use App\Models\Commentaires;
use App\Models\User;
use Illuminate\Auth\Access\Response;
class CommentairesPolicy
{
/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return false;
}
/**
* Determine whether the user can view the model.
*/
public function view(User $user, Commentaires $commentaires): bool
{
return false;
}
/**
* Determine whether the user can create models.
*/
public function create(User $user): bool
{
return false;
}
/**
* Determine whether the user can update the model.
*/
public function update(User $user, Commentaires $commentaires): bool
{
return false;
}
/**
* Determine whether the user can delete the model.
*/
public function delete(User $user, Commentaires $commentaires): bool
{
return false;
}
/**
* Determine whether the user can restore the model.
*/
public function restore(User $user, Commentaires $commentaires): bool
{
return false;
}
/**
* Determine whether the user can permanently delete the model.
*/
public function forceDelete(User $user, Commentaires $commentaires): bool
{
return false;
}
}

View File

@@ -1,12 +1,15 @@
<?php
use Illuminate\Support\Facades\Log;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
@@ -14,5 +17,8 @@ return Application::configure(basePath: dirname(__DIR__))
//
})
->withExceptions(function (Exceptions $exceptions) {
//
$exceptions->renderable(function (NotFoundHttpException $e) {
Log::channel('projectLog')->error('Resource not found: '.$e->getMessage());
return response()->json(['message' => 'Resource not found'], 404);
});
})->create();

View File

@@ -8,6 +8,7 @@
"require": {
"php": "^8.2",
"laravel/framework": "^12.0",
"laravel/sanctum": "^4.0",
"laravel/tinker": "^2.10.1"
},
"require-dev": {

102
laravel/composer.lock generated
View File

@@ -4,20 +4,20 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "88970a0117c062eed55fa8728fc43833",
"content-hash": "85c1d2065f70e38b0d6bf66559fb13c5",
"packages": [
{
"name": "brick/math",
"version": "0.12.3",
"version": "0.13.1",
"source": {
"type": "git",
"url": "https://github.com/brick/math.git",
"reference": "866551da34e9a618e64a819ee1e01c20d8a588ba"
"reference": "fc7ed316430118cc7836bf45faff18d5dfc8de04"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/brick/math/zipball/866551da34e9a618e64a819ee1e01c20d8a588ba",
"reference": "866551da34e9a618e64a819ee1e01c20d8a588ba",
"url": "https://api.github.com/repos/brick/math/zipball/fc7ed316430118cc7836bf45faff18d5dfc8de04",
"reference": "fc7ed316430118cc7836bf45faff18d5dfc8de04",
"shasum": ""
},
"require": {
@@ -56,7 +56,7 @@
],
"support": {
"issues": "https://github.com/brick/math/issues",
"source": "https://github.com/brick/math/tree/0.12.3"
"source": "https://github.com/brick/math/tree/0.13.1"
},
"funding": [
{
@@ -64,7 +64,7 @@
"type": "github"
}
],
"time": "2025-02-28T13:11:00+00:00"
"time": "2025-03-29T13:50:30+00:00"
},
{
"name": "carbonphp/carbon-doctrine-types",
@@ -1056,20 +1056,20 @@
},
{
"name": "laravel/framework",
"version": "v12.16.0",
"version": "v12.17.0",
"source": {
"type": "git",
"url": "https://github.com/laravel/framework.git",
"reference": "293bb1c70224faebfd3d4328e201c37115da055f"
"reference": "8729d084510480fdeec9b6ad198180147d4a7f06"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/framework/zipball/293bb1c70224faebfd3d4328e201c37115da055f",
"reference": "293bb1c70224faebfd3d4328e201c37115da055f",
"url": "https://api.github.com/repos/laravel/framework/zipball/8729d084510480fdeec9b6ad198180147d4a7f06",
"reference": "8729d084510480fdeec9b6ad198180147d4a7f06",
"shasum": ""
},
"require": {
"brick/math": "^0.11|^0.12",
"brick/math": "^0.11|^0.12|^0.13",
"composer-runtime-api": "^2.2",
"doctrine/inflector": "^2.0.5",
"dragonmantank/cron-expression": "^3.4",
@@ -1267,7 +1267,7 @@
"issues": "https://github.com/laravel/framework/issues",
"source": "https://github.com/laravel/framework"
},
"time": "2025-05-27T15:49:44+00:00"
"time": "2025-06-03T14:04:18+00:00"
},
{
"name": "laravel/prompts",
@@ -1328,6 +1328,70 @@
},
"time": "2025-02-11T13:34:40+00:00"
},
{
"name": "laravel/sanctum",
"version": "v4.1.1",
"source": {
"type": "git",
"url": "https://github.com/laravel/sanctum.git",
"reference": "a360a6a1fd2400ead4eb9b6a9c1bb272939194f5"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/laravel/sanctum/zipball/a360a6a1fd2400ead4eb9b6a9c1bb272939194f5",
"reference": "a360a6a1fd2400ead4eb9b6a9c1bb272939194f5",
"shasum": ""
},
"require": {
"ext-json": "*",
"illuminate/console": "^11.0|^12.0",
"illuminate/contracts": "^11.0|^12.0",
"illuminate/database": "^11.0|^12.0",
"illuminate/support": "^11.0|^12.0",
"php": "^8.2",
"symfony/console": "^7.0"
},
"require-dev": {
"mockery/mockery": "^1.6",
"orchestra/testbench": "^9.0|^10.0",
"phpstan/phpstan": "^1.10",
"phpunit/phpunit": "^11.3"
},
"type": "library",
"extra": {
"laravel": {
"providers": [
"Laravel\\Sanctum\\SanctumServiceProvider"
]
}
},
"autoload": {
"psr-4": {
"Laravel\\Sanctum\\": "src/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Taylor Otwell",
"email": "taylor@laravel.com"
}
],
"description": "Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.",
"keywords": [
"auth",
"laravel",
"sanctum"
],
"support": {
"issues": "https://github.com/laravel/sanctum/issues",
"source": "https://github.com/laravel/sanctum"
},
"time": "2025-04-23T13:03:38+00:00"
},
{
"name": "laravel/serializable-closure",
"version": "v2.0.4",
@@ -5846,16 +5910,16 @@
},
{
"name": "filp/whoops",
"version": "2.18.0",
"version": "2.18.1",
"source": {
"type": "git",
"url": "https://github.com/filp/whoops.git",
"reference": "a7de6c3c6c3c022f5cfc337f8ede6a14460cf77e"
"reference": "8fcc6a862f2e7b94eb4221fd0819ddba3d30ab26"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/filp/whoops/zipball/a7de6c3c6c3c022f5cfc337f8ede6a14460cf77e",
"reference": "a7de6c3c6c3c022f5cfc337f8ede6a14460cf77e",
"url": "https://api.github.com/repos/filp/whoops/zipball/8fcc6a862f2e7b94eb4221fd0819ddba3d30ab26",
"reference": "8fcc6a862f2e7b94eb4221fd0819ddba3d30ab26",
"shasum": ""
},
"require": {
@@ -5905,7 +5969,7 @@
],
"support": {
"issues": "https://github.com/filp/whoops/issues",
"source": "https://github.com/filp/whoops/tree/2.18.0"
"source": "https://github.com/filp/whoops/tree/2.18.1"
},
"funding": [
{
@@ -5913,7 +5977,7 @@
"type": "github"
}
],
"time": "2025-03-15T12:00:00+00:00"
"time": "2025-06-03T18:56:14+00:00"
},
{
"name": "hamcrest/hamcrest-php",

View File

@@ -0,0 +1,84 @@
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(),
// Sanctum::currentRequestHost(),
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
],
];

View File

@@ -0,0 +1,27 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Billet>
*/
class BilletFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'BIL_DATE' => $this->faker->date(),
'BIL_TITRE' => $this->faker->text(20),
'BIL_CONTENU' => $this->faker->text(100),
'created_at' => now(),
'updated_at' => now(),
];
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Commentaires>
*/
class CommentairesFactory extends Factory
{
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'COM_DATE' => now(),
'COM_CONTENU' => fake()->text(200),
'billet_id' => fake()->numberBetween(1, 10),
'user_id' => fake()->numberBetween(1, 2),
];
}
}

View File

@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->string('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('billets', function (Blueprint $table) {
$table->id();
$table->date('BIL_DATE');
$table->text('BIL_TITRE');
$table->text('BIL_CONTENU');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('billets');
}
};

View File

@@ -0,0 +1,41 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('commentaires', function (Blueprint $table) {
$table->id();
$table->date('COM_DATE');
$table->text('COM_CONTENU');
$table->unsignedBigInteger('billet_id');
$table->unsignedBigInteger('user_id');
$table->foreign('billet_id')
->references('id')
->on('billets')
->onDelete('cascade')
->onUpdate('cascade');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade')
->onUpdate('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('commentaires');
}
};

View File

@@ -0,0 +1,18 @@
<?php
namespace Database\Seeders;
use App\Models\Billet;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class BilletSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
Billet::factory(10)->create();
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Database\Seeders;
use App\Models\Commentaire;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class CommentairesSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
Commentaire::factory(10)->create();
}
}

View File

@@ -11,13 +11,11 @@ class DatabaseSeeder extends Seeder
/**
* Seed the application's database.
*/
public function run(): void
{
// User::factory(10)->create();
public function run(): void{
User::factory()->create([
'name' => 'Test User',
'email' => 'test@example.com',
]);
// User::factory()->create([
// 'name' => 'Test User',
// 'email' => 'test@example.com',
// ]);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Database\Seeders;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class UserSeeder extends Seeder
{
/**
* Run the database seeds.
*/
public function run(): void
{
User::factory(2)->create();
}
}

35
laravel/routes/api.php Executable file
View File

@@ -0,0 +1,35 @@
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Hash;
// Make sure BilletController exists at app/Http/Controllers/BilletController.php
use App\Http\Controllers\BilletController;
Route::middleware('auth:sanctum')->group(function () {
Route::get('/user', [\App\Http\Controllers\UserController::class, 'show']);
Route::post('/user/logout', function (Request $request) {
$request->user()->tokens()->delete();
});
Route::get('/billets/{id}', [BilletController::class, 'show'])->whereNumber('id');
Route::post('/commentaires', [\App\Http\Controllers\CommentaireController::class, 'store']);
});
Route::post('/register', [\App\Http\Controllers\UserController::class, 'store']);
Route::post('/login', function (Request $request) {
$request->validate([
'email' => 'required|email|max:50',
'password' => 'required|string|min:8',
]);
$user = \App\Models\User::where('email', $request->email)->first();
if (!$user || !Hash::check($request->password, $user->password)) {
throw \Illuminate\Validation\ValidationException::withMessages([
'email' => ['The provided credentials are incorrect.'],
]);
}
return $user->createToken('auth_token')->plainTextToken;
});