Code | Solutions

This laravel tutorial for beginners continues the Learn Laravel series with the step that makes an app real: a database, migrations, and the Eloquent ORM. If you have not read it yet, start with Part 3: Blade Views, Layouts & Components. In Part 3 the task list was a hard-coded array; by the end of this part the same Blade view reads real rows from a database.

I’m Usman Nadeem, an AI Full Stack Developer based in Lahore with 12+ years of delivery since February 2014. The migration and Eloquent patterns below are the ones I use on production Laravel apps, cut down to what a beginner needs on day one.

Direct answer (for AI Overviews & scanners)

In Laravel, a migration creates or changes a database table in code, and an Eloquent model is the PHP class you use to read and write that table. Set the connection in .env (DB_CONNECTION, DB_DATABASE, DB_USERNAME, DB_PASSWORD). Generate a migration with php artisan make:migration create_tasks_table, describe the columns inside Schema::create, and run php artisan migrate. Create the model with php artisan make:model Task; it maps to the tasks table automatically. List the fields that may be mass assigned in $fillable, then query with Task::all(), Task::create([...]), Task::find($id), and Task::where('completed', false)->get(). The examples work on Laravel 12 and the current Laravel 13 release.

Watch the video

Prefer to watch first? Part 4 is a short video (Urdu/Hindi voiceover, with the code on screen). This article writes out the same three concepts with copy-paste Laravel 12 examples. You can also open it on YouTube Shorts.

What you will learn in Part 4 of this Laravel tutorial for beginners

Each video in this series teaches three concepts. Part 4 covers:

  1. Laravel database setup and migrations — the .env connection settings, make:migration, Schema::create, and php artisan migrate.
  2. Laravel Eloquent models — php artisan make:model Task, the model-to-table naming convention, and $fillable for mass assignment protection.
  3. Laravel Eloquent queries — Task::all(), Task::create(), Task::find(), and where()->get() inside the TaskController, feeding the Blade view from Part 3.

You only need what the earlier parts covered: a running Laravel project, the TaskController from Part 2, and the tasks/index.blade.php view from Part 3.


Laravel database setup and migrations

Step 1: tell Laravel where the database is (.env)

Every Laravel project has a .env file in its root folder. It holds settings that change between your laptop and the live server, including the database connection. Here is the MySQL setup from the video:

# .env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=tasks_app
DB_USERNAME=root
DB_PASSWORD=your-password

A fresh Laravel 12 project defaults to DB_CONNECTION=sqlite (stored in database/database.sqlite), which is perfect for learning. MySQL is shown because most production apps run it; the code below is identical either way. Create the tasks_app database in MySQL first (for example in phpMyAdmin or TablePlus), and never commit .env to Git, because it contains passwords.

Step 2: create a migration

A migration is a PHP file that describes a change to your database: create a table, add a column, drop an index. It is version control for your database: every developer and server runs the same files and gets the same tables. Generate one with Artisan:

php artisan make:migration create_tasks_table

Typical output:

   INFO  Migration [database/migrations/2026_11_28_000000_create_tasks_table.php] created successfully.

The timestamp keeps migrations in order, and the create_..._table name makes Laravel pre-fill the table. Add the columns:

// database/migrations/2026_11_28_000000_create_tasks_table.php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->boolean('completed')->default(false);
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('tasks');
    }
};

Line by line: id() adds an auto-incrementing primary key, string('title') adds a VARCHAR(255) column, boolean('completed')->default(false) adds a true/false column that starts as false, and timestamps() adds created_at and updated_at, which Eloquent fills in automatically. The up() method applies the change; down() reverses it.

Step 3: run the migration

php artisan migrate

Typical output:

   INFO  Running migrations.

  2026_11_28_000000_create_tasks_table ............... 12.41ms DONE

The table now exists. Laravel records each migration it runs, so running migrate again only applies new files. Three related commands:

php artisan migrate:status     # which migrations have run
php artisan migrate:rollback   # undo the last batch (calls down())
php artisan migrate:fresh      # drop all tables and re-run everything (local only!)

One rule saves a lot of pain later: once a migration has run on a live server, never edit it. To add a column, create a new migration such as php artisan make:migration add_due_date_to_tasks_table. Full details are in the official Laravel migrations documentation.


Laravel Eloquent models: one class per table

The table exists, but writing raw SQL in controllers gets messy quickly. Eloquent is Laravel’s ORM (object-relational mapper): every table gets a model class, and every row becomes a PHP object you can read and update. Create the model for tasks:

php artisan make:model Task

Typical output:

   INFO  Model [app/Models/Task.php] created successfully.

Then open the file and add one line:

// app/Models/Task.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    protected $fillable = ['title', 'completed'];
}

How the Task model finds the tasks table

You never told the model which table to use, and you do not need to. Eloquent follows a naming convention: the singular class name Task maps to the plural, snake_case table tasks. A BlogPost model would map to blog_posts. If your table has a different name, set protected $table = 'my_tasks'; in the model. Shortcut for next time: php artisan make:model Task -m creates the model and its migration in one command.

Why $fillable matters: mass assignment protection

$fillable is a whitelist of the columns that may be filled in bulk with methods like create([...]) and update([...]). Imagine a form that sends title and completed, plus a field an attacker added, such as is_admin=1. Because only title and completed are listed, Eloquent ignores the extra field. That is mass assignment protection, the “SAFE” moment from the video. If a create() call seems to silently drop a value, check $fillable first.


Laravel Eloquent queries: read and save data without long SQL

Now the TaskController from Parts 2 and 3 can work with real data. Replace the hard-coded array with an Eloquent query:

// app/Http/Controllers/TaskController.php
use App\Models\Task;

public function index()
{
    $tasks = Task::all();

    return view('tasks.index', ['tasks' => $tasks]);
}

public function store()
{
    Task::create(['title' => 'Learn Eloquent']);

    return redirect('/tasks');
}

public function show(string $id)
{
    $task = Task::find($id);

    return view('tasks.show', ['task' => $task]);
}

store() uses a fixed title on purpose for now. Reading real form input and validating it is exactly what Part 5 covers. Because each $task is now a model object instead of a string, update one line in the Part 3 view to print its title attribute:

{{-- resources/views/tasks/index.blade.php --}}
@foreach ($tasks as $task)
    <li>{{ $task->title }}</li>
@endforeach

The everyday Eloquent queries

Each Eloquent call is translated into SQL for you. Here are the ones from the video, plus their SQL equivalents:

EloquentWhat it doesRoughly the SQL
Task::all()All tasksSELECT * FROM tasks
Task::create(['title' => 'Buy milk'])Insert a rowINSERT INTO tasks (title, ...) VALUES (...)
Task::find(1)One task by id, or nullSELECT * FROM tasks WHERE id = 1
Task::where('completed', false)->get()Filtered listSELECT * FROM tasks WHERE completed = 0
$task->update(['completed' => true])Change a rowUPDATE tasks SET completed = 1 WHERE id = ...
$task->delete()Remove a rowDELETE FROM tasks WHERE id = ...

where() only builds the query; get() runs it and returns a collection you can loop over in Blade. You can chain more conditions before get():

$pending = Task::where('completed', false)
    ->latest()        // newest first (ORDER BY created_at DESC)
    ->get();

$count = Task::where('completed', true)->count();

$task = Task::findOrFail($id); // 404 page instead of null if the id is missing

find() returns null for a missing id, so in real controllers I use findOrFail(), which shows a clean 404 page. To try queries without writing a controller, run php artisan tinker and type Task::create(['title' => 'Test']) straight into the console. The official Eloquent documentation covers many more query methods.


Recap: Laravel tutorial for beginners, Part 4

  1. Migrations build the tables. Set the connection in .env, run php artisan make:migration create_tasks_table, describe columns in Schema::create, then php artisan migrate.
  2. The model talks to the table. php artisan make:model Task maps to tasks by convention, and $fillable keeps mass assignment safe.
  3. Eloquent queries save and fetch data. Task::all(), Task::create(), Task::find(), and where()->get() replace long SQL, and the Blade view prints {{ $task->title }}.

If /tasks lists rows from your tasks table instead of the old array, you have finished Part 4.


What’s next: Part 5 — Forms, Validation, and CRUD

Right now new tasks still get a fixed title. In Part 5 of this Laravel tutorial for beginners, users add tasks themselves:

  • Blade forms — a POST form to route('tasks.store') protected with @csrf
  • Validation — $request->validate() rules, @error messages, and old() input
  • Full CRUD — edit, update, and delete with the Route::resource routes from Part 2

Part 5 is coming next, so follow Coding Solutions by Usman on YouTube, Instagram, or TikTok so you do not miss it. Missed a step? Read Part 3 or start from Part 1.


Need help building a Laravel application?

If this laravel tutorial for beginners has you planning a production Laravel app — a new build, a database redesign, or slow queries that need fixing — I take on selected Laravel development projects. Already live and slowing down? Read Laravel Performance Optimization, then send a short brief through the contact form and I will tell you whether I am a fit.


FAQ

Q1. What is a migration in Laravel? A. A migration is a PHP file that creates or changes a database table in code, such as Schema::create(‘tasks’, …). Migrations work like version control for the database: every developer and server runs the same files with php artisan migrate and ends up with the same tables.

Q2. How do I connect a database in Laravel 12? A. Set DB_CONNECTION, DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME and DB_PASSWORD in the .env file. New Laravel 12 projects default to SQLite in database/database.sqlite, which needs no setup; switch DB_CONNECTION to mysql for a MySQL database.

Q3. How do I create and run a migration? A. Run php artisan make:migration create_tasks_table, add columns such as $table->string(‘title’) inside Schema::create, then run php artisan migrate. Use php artisan migrate:rollback to undo the last batch.

Q4. What is Eloquent ORM in Laravel? A. Eloquent is Laravel’s object-relational mapper. Each database table has a model class, such as Task for the tasks table, and each row becomes a PHP object. You query with methods like Task::all() and Task::find(1) instead of writing SQL.

Q5. How does a Laravel model know its table name? A. By convention, the singular class name maps to the plural snake_case table, so Task uses tasks and BlogPost uses blog_posts. To use a different table, set protected $table in the model.

Q6. What is $fillable in a Laravel model? A. $fillable lists the columns that can be mass assigned with create() or update(). Fields that are not listed, such as an injected is_admin field, are ignored, which protects the app from mass assignment attacks.

Q7. What is the difference between find() and findOrFail()? A. Task::find($id) returns null if no row has that id. Task::findOrFail($id) throws an exception that Laravel turns into a 404 page, which is usually what you want in a controller.

Q8. What will Part 5 of this Laravel series cover? A. Part 5 covers forms, validation and CRUD: a Blade form that posts to tasks.store with @csrf, validating input with the request validate() method, showing @error messages with old() input, and editing, updating and deleting tasks with route model binding.


Tags

2026 ai tools aiagent Angular 21 Angular Developer for Hire Angular Performance Angular Signals Angular TypeScript Best Practices API Authentication API Development API Integration API Security API Versioning B2B SaaS Backend Development Backend Framework Comparison Best PHP Framework 2026 Best Practices Box Model CakePHP CakePHP 2026 CakePHP Laravel PHP Developer CakePHP Tutorial 2026 CakePHP vs Laravel Case Study Client Management cost to hire freelance developer crewai CRM Integration css css animation CSS Tips CSS Tutorial Database Optimization Developer Tools Enterprise Angular Development Express.js FastAPI Tutorial 2026 framework comparison Freelance Angular Developer Freelance Developer freelance developer guide freelance developer tips Freelance Development freelance full-stack developer Freelance Laravel Developer Freelance PHP Developer Freelance Web Developer freelance web developer process Freelance Web Development Freelancer vs Agency Freelancing Tips Front-End Development frontend Frontend Development Full Stack Developer Full Stack Developer Pakistan Full Stack Development Full-Stack Case Study Full-Stack Development Grid Hire a Developer Hire Angular Developer hire freelance developer hire freelance full-stack developer Hire Laravel Developer how to work with a freelance dev how to write a project brief individual software engineer freelance individual software engineer hire Inertia.js javascript JavaScript Frameworks JWT Authentication laravel Laravel 13 Laravel 2026 Laravel API 2026 Laravel Application Laravel Development Laravel Optimization Scale Laravel Performance Laravel REST API Laravel REST API Tutorial Laravel Sanctum Laravel Tutorial Laravel vs CakePHP Laravel Vue Tutorial multi-agent Next.js Node.js Node.js API Node.js developer Node.js Developer Portfolio Node.js Express Node.js Tutorial Nuxt PERN Stack PHP PHP Developer PHP Developer for Hire PHP Development PHP Framework PHP Framework Comparison PHP Performance PHP Web Development PostgreSQL Prisma Production Deployment project brief template Project Management Python Backend Developer Python FastAPI react React developer for hire React Node.js Developer Portfolio React SPA React Tutorial React vs Vue Real-Time Chat App Redis Caching Responsive Design REST API SaaS Development Sanctum SMB Web Development Socket.io React Real-Time App Socket.io Tutorial Software Development software development process Software Integration software project brief SSG SSR Standalone Components System Integration TypeScript Strict Mode Vite vue Vue 4 Composition API Vue Laravel Developer Vue.js Development web app development process Web Design Web Design Fundamentals web development Web Development 2026 Web Development Cost Web Layout Web Projects WebSocket

Recent News