-
Create Laravel application
laravel new api-advertisement
OR
composer create-project laravel/laravel api-advertisement
-
Update the create_users_table migration
Add
$table->boolean('is_admin')->default(false);
to the codeThe database/migrations/0001_01_01_000000_create_users_table.php file content will become
<?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('users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->boolean('is_admin')->default(false); $table->rememberToken(); $table->timestamps(); }); Schema::create('password_reset_tokens', function (Blueprint $table) { $table->string('email')->primary(); $table->string('token'); $table->timestamp('created_at')->nullable(); }); Schema::create('sessions', function (Blueprint $table) { $table->string('id')->primary(); $table->foreignId('user_id')->nullable()->index(); $table->string('ip_address', 45)->nullable(); $table->text('user_agent')->nullable(); $table->longText('payload'); $table->integer('last_activity')->index(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('users'); Schema::dropIfExists('password_reset_tokens'); Schema::dropIfExists('sessions'); } };
-
Create Two users
In the
database/seeders/DatabaseSeeder.php
add the following codeUser::factory()->create([ 'name' => 'Super User', 'email' => '[email protected]', 'password' => bcrypt('password'), 'is_admin' => true, ]); User::factory()->create([ 'name' => 'Another User', 'email' => '[email protected]', 'password' => bcrypt('password'), ]);
The entire code will become
database/seeders/DatabaseSeeder.php
<?php namespace Database\Seeders; use App\Models\Advertisement; use App\Models\User; // use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. */ public function run(): void { // User::factory(10)->create(); User::factory()->create([ 'name' => 'Super User', 'email' => '[email protected]', 'password' => bcrypt('password'), 'is_admin' => true, ]); User::factory()->create([ 'name' => 'Another User', 'email' => '[email protected]', 'password' => bcrypt('password'), ]); } }
-
Make Advertisement Model, Migration for the model and Controller with resource methods for the model
Terminal
php artisan make:model Advertisement -mcr
-
Update the migration file to define the structure of our advertisement
Add the following code in
database/migrations/timestamp_create_advertisements_table.php
$table->string('title'); $table->string('content'); $table->string('image_path')->nullable(); $table->boolean('is_approved')->default(false); $table->foreignIdFor(User::class);
-
You need to add
use App\Models\User;
On the top of the page
The full code will looks like
database/migrations/timestamp_create_advertisements_table.php
<?php use App\Models\User; 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('advertisements', function (Blueprint $table) { $table->id(); $table->string('title'); $table->string('content'); $table->string('image_path')->nullable(); $table->boolean('is_approved')->default(false); $table->foreignIdFor(User::class)->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. */ public function down(): void { Schema::dropIfExists('advertisements'); } };
-
-
Run the migration
Terminal
php artisan migrate
Note:
user_id column will be created by
$table->foreignIdFor(User::class);
-
Add another seeder to create a dummy advertisement data
database/seeders/DatabaseSeeder.php
-
Advertisement::create([ 'title' => 'Virthli', 'content' => 'MZU will be organizing Virthli, everyone is invited to come. Ticket will be available by the main gate', 'is_approved' => true, 'user_id' => 1 ]); Advertisement::create([ 'title' => 'Software Engineer Job Vacant', 'content' => 'A full-stack software engineer job vacnt in Microsoft mizoram branch', 'is_approved' => true, 'user_id' => 2 ]); Advertisement::create([ 'title' => 'Programming Course', 'content' => 'A full-stack programming 6 months course is open contact 123456789 for detail', 'is_approved' => false, 'user_id' => 2 ]);
Wih the existing one. The entire DatabaseSeeder.php file will look like
-
<?php namespace Database\Seeders; use App\Models\Advertisement; use App\Models\User; // use Illuminate\Database\Console\Seeds\WithoutModelEvents; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. */ public function run(): void { // User::factory(10)->create(); User::factory()->create([ 'name' => 'Super User', 'email' => '[email protected]', 'password' => bcrypt('password'), 'is_admin' => true, ]); User::factory()->create([ 'name' => 'Another User', 'email' => '[email protected]', 'password' => bcrypt('password'), ]); Advertisement::create([ 'title' => 'Virthli', 'content' => 'MZU will be organizing Virthli, everyone is invited to come. Ticket will be available by the main gate', 'is_approved' => true, 'user_id' => 1 ]); Advertisement::create([ 'title' => 'Software Engineer Job Vacant', 'content' => 'A full-stack software engineer job vacnt in Microsoft mizoram branch', 'is_approved' => true, 'user_id' => 2 ]); Advertisement::create([ 'title' => 'Programming Course', 'content' => 'A full-stack programming 6 months course is open contact 123456789 for detail', 'is_approved' => false, 'user_id' => 2 ]); } }
-
Run the seeder
Terminal
```plaintext
php artisan db:seed
```
This will create admin user, another user and the three advertisement entries.
- Add a method to fetch the advertisements
In `app/Http/Controllers/AdvertisementController.php` update the index() method
```php
public function index()
{
return Advertisement::all();
}
```
- Generate api route
Terminal
```plaintext
php artisan install:api
```
Run the migration.
- Create a route to fetch the advertisements
in theroutes/api.php
file, Add
```php
Route::apiResource('/', function () {
return view('welcome');
});
```
This will create all the required endpoints to utilize/access the api resource methods.
- Then, you will be able to access the dummy data from the web page
Click [HERE](http://127.0.0.1:8000/api/advertisements) to view the data returned by the api
-
Add a method to store the advertisements
In
app/Http/Controllers/AdvertisementController.php
update the store() methodpublic function store(Request $request) { $validated = $request->validate([ 'title' => 'required', 'content' => 'required', 'is_approved' => 'nullable', ]); $validated['user_id'] = request()?->user()?->id ?? null; Advertisement::create($validated); return $this->index(); }
Note:
the Route::apiResource('advertisements') method called in `routes/api.php` already defined the route for this store and all other required methods for api Advertisement routes.
-
Add a method to store the advertisements
-
In
app/Http/Controllers/AdvertisementController.php
update the update() methodpublic function update(Request $request, Advertisement $advertisement) { $validated = $request->validate([ 'title' => 'required', 'content' => 'required', 'is_approved' => 'nullable', ]); $advertisement->update($validated); return $this->index(); }
-
In
app/Http/Controllers/AdvertisementController.php
update the destroy() methodpublic function update(Advertisement $advertisement) { $advertisement->delete(); return $this->index(); }
-
Now the entire AdvertisementController.php file will have the following content
<?php namespace App\Http\Controllers; use App\Models\Advertisement; use Illuminate\Http\Request; class AdvertisementController extends Controller { /** * Display a listing of the resource. */ public function index() { return Advertisement::all(); } /** * Show the form for creating a new resource. */ public function create() { // } /** * Store a newly created resource in storage. */ public function store(Request $request) { $validated = $request->validate([ 'title' => 'required', 'content' => 'required', 'is_approved' => 'nullable', ]); $validated['user_id'] = request()?->user()->id ?? null; Advertisement::create($validated); return $this->index(); } /** * Display the specified resource. */ public function show(Advertisement $advertisement) { // } /** * Show the form for editing the specified resource. */ public function edit(Advertisement $advertisement) { // } /** * Update the specified resource in storage. */ public function update(Request $request, Advertisement $advertisement) { $validated = $request->validate([ 'title' => 'required', 'content' => 'required', 'is_approved' => 'nullable', ]); $advertisement->update($validated); return $this->index(); } /** * Remove the specified resource from storage. */ public function destroy(Advertisement $advertisement) { $advertisement->delete(); return $this->index(); } }