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/ProductControllerphp 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...