←Back

The difference explained;

Controllers, models and resources are used constantly as users interact with your app, whereas database migrations and database seeders are used when setting up the app to create and populate the database.

Resources, Controllers and models;

Controllers handle incoming requests, validate incoming data, and finally (optionally) send back data according to the structure in a certain resource (the following controller doesn’t do a whole lot and uses inertia, but that’s optional. For more controller functions, refer to https://www.notion.so/Showing-Creating-and-updating-records-1d1bb3b2e780802d9404de9d2e1231a9?pvs=4

class CuisineController extends Controller
{
    /**
     * Display a listing of the cuisines.
     */
    public function index()
    {
        $cuisines = Cuisine::all();
        return Inertia::render('Cuisines/Index', [
            'cuisines' => $cuisines,
        ]);
    }

    /**
     * Show the form for creating a new cuisine.
     */
    public function create()
    {
        return Inertia::render('Cuisines/Create');
    }

    /**
     * Store a newly created cuisine in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'continent' => 'required|string|max:255',
        ]);

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

        return redirect()->route('cuisines.index')->with('success', 'Cuisine created successfully.');
    }

    /**
     * Display the specified cuisine.
     */
    public function show(Cuisine $cuisine)
    {
        return Inertia::render('Cuisines/Show', [
            'cuisine' => $cuisine,
        ]);
    }

    /**
     * Show the form for editing the specified cuisine.
     */
    public function edit(Cuisine $cuisine)
    {
        return Inertia::render('Cuisines/Edit', [
            'cuisine' => $cuisine,
        ]);
    }

    /**
     * Update the specified cuisine in storage.
     */
    public function update(Request $request, Cuisine $cuisine)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'continent' => 'required|string|max:255',
        ]);

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

        return redirect()->route('cuisines.index')->with('success', 'Cuisine updated successfully.');
    }

    /**
     * Remove the specified cuisine from storage.
     */
    public function destroy(Cuisine $cuisine)
    {
        $cuisine->delete();

        return redirect()->route('cuisines.index')->with('success', 'Cuisine deleted successfully.');
    }
}

Resources determine how data comes back to your view (this will become a json object). Before the return part, you can write more complicated functions/links with auth etc. The functions you see in the return part (e.g. ‘isfavoritedbycurrentuser) are found in the corresponding models

return [
      'id' => $this->id,
      'name' => $this->name,
      'description' => $this->description,
      'ingredients' => json_decode($this->ingredients, true),
      'ingredients2' => $ingredients2,
      'user_id' => $this->user_id,
      'cuisine_id' => $this->cuisine_id,
      'cuisine' => new CuisineResource($this->whenLoaded('cuisine')),
      'favorite' => $this->isFavoritedByCurrentUser(),
      'editable' => $this->user_id === $currentUserId && $this->user_id !== null,
      'is_own' => $this->user_id === $currentUserId && $this->user_id !== null,
      // $this->cuisine->name : null, // Include the cuisine name
      'avatar' => $this?->getFirstMediaUrl('avatars'),
  ];

Models can explain relationships between various tables; (hasmany, belongstomany, or custom ones;) Refer to eloquent relationships note

class Mixes extends Model implements HasMedia
{
    use HasFactory;
    use InteractsWithMedia;

    protected $fillable = ['name', 'ingredients', 'description', 'user_id', 'cuisine_id'];

    // Define the relationship with the Cuisine model
    public function cuisine()
    {
        return $this->belongsTo(Cuisine::class, 'cuisine_id');
    }
    public function ingredients(): HasMany
    {
        return $this->hasMany(Ingredient::class);
    }
    public function favoritedBy()
    {
        return $this->belongsToMany(User::class, 'mix_user', 'mix_id', 'user_id');
    }
    public function isFavoritedByCurrentUser()
    {
        $currentUserId = Auth::id();
        return $this->favoritedBy()->where('user_id', $currentUserId)->exists();
    }
}

To create these models, controllers and resources, refer to ;

https://www.notion.so/Creating-models-controllers-resources-etc-1cabb3b2e7808099afe6e397163cb73f?pvs=4

Migrations create the table structures when setting up your app.


return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('cuisines', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('color');
            $table->string('continent')->default('Unknown');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('cuisines');
    }
};

Seeders determine the table content (if applicable). They can be defined directly or import SQL tables or CSV files. Example for the measures;

<?php

namespace Database\\Seeders;

use Illuminate\\Database\\Console\\Seeds\\WithoutModelEvents;
use Illuminate\\Database\\Seeder;
use Illuminate\\Support\\Facades\\DB;

class MeasuresTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run()
    {
        DB::table('measures')->insert([
            [
                'name' => 'Tbsp',
                'info' => 'Tablespoon',
                'created_at' => now(),
                'updated_at' => now(),
            ],
            ['name' => 'Ts', 'info' => 'Teaspoon', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Pinches', 'info' => 'Pinch', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Cups', 'info' => 'Cup', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Gr', 'info' => 'Grams', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'Kg', 'info' => 'Kilograms', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'ml', 'info' => 'millilitres', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'dl', 'info' => 'decilitre', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'l', 'info' => 'litre', 'created_at' => now(), 'updated_at' => now()],
            ['name' => 'piece(s)', 'info' => 'piece', 'created_at' => now(), 'updated_at' => now()],
        ]);
    }
}

Have a look through the files in the project (app, app/http and app/database folders) to get a better sense of what these look like.