Courses

How to Build Laravel 12 API From Scratch

List inside of List: Multi-Level Data

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Creating products table with category relationship
- Handling relationships in API responses
- Using API Resource inside other API Resource
- Managing eager loading with whenLoaded() in the API Resource

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

In this lesson, we will discuss relationships between tables and between Eloquent Models and how to return them from the API Resources.


First, we must create a new Model to have a relation with a category.

php artisan make:model Product -mf

database/migration/xxx_create_products_table.php:

public function up(): void
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->foreignId('category_id')->constrained();
$table->string('name');
$table->text('description');
$table->integer('price');
$table->timestamps();
});
}

app/Models/Product.php:

use Illuminate\Database\Eloquent\Relations\BelongsTo;
 
class Product extends Model
{
use HasFactory;
 
protected $fillable = [
'name',
'description',
'price',
];
 
public function category(): BelongsTo
{
return $this->belongsTo(Category::class);
}
}

database/factories/ProductFactory.php:

use App\Models\Category;
 
class ProductFactory extends Factory
{
public function definition(): array
{
return [
'name' => fake()->word(),
'category_id' => Category::inRandomOrder()->first()->id,
'description' => fake()->paragraph(),
'price' => rand(1000, 99999),
];
}
}

database/seeders/DatabaseSeeder.php:

 
use App\Models\Product;
 
class DatabaseSeeder extends Seeder
{
public function run(): void
{
Category::factory(10)->create();
Product::factory(20)->create();
}
}

And run the migrations with the seed.

php artisan migrate:fresh --seed

Next, the Controller, Resource, and Route.

php artisan make:controller Api/ProductController
php artisan make:resource ProductResource

routes/api.php:

Route::get('/user', function (Request $request) {
return $request->user();
})->middleware(Authenticate::using('sanctum'));
 
Route::get('categories', [\App\Http\Controllers\Api\CategoryController::class, 'index']);
Route::get('categories/{category}', [\App\Http\Controllers\Api\CategoryController::class, 'show']);
 
Route::get('products', [\App\Http\Controllers\Api\ProductController::class, 'index']);

In the Controller, we can return the product...

The full lesson is only for Premium Members.
Want to access all 28 video+text lessons of this course? (1 h 21 min)

You also get:

  • 83 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord