Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

PHP
PHP
0/12 completed
Beginner
Hello PHPVariables and arraysControl flowFunctions
Intermediate
Strings, dates and JSONForms, requests and sessionsDatabases with PDO
Advanced
Object-oriented PHPErrors, exceptions and typesSecurity essentials
Pro
Composer, autoloading and testingLaravel basics
Tracks / PHP / Pro

Laravel basics

Laravel is the most popular PHP framework, and one of the most loved web frameworks in any language. It gives you routing, a database layer (Eloquent), templates (Blade), validation, authentication, queues, email and more, all designed to work together, with excellent documentation. If you're building a web application in PHP today, Laravel is the usual choice.

💡 Laravel runs on a server, not in the browser. Every command below was run with PHP 8.5 and Composer on Linux, with the output shown underneath, so you can follow along on your own computer.

Creating a project

bash
composer create-project laravel/laravel blog --no-interaction --quiet --prefer-dist 2>/dev/null
cd blog
php artisan --version
ls
Output
Laravel Framework 13.43.0
AGENTS.md  artisan	  config	public	   tests
CLAUDE.md  bootstrap	  database	resources  vendor
README.md  composer.json  package.json	routes	   vite.config.js
app	   composer.lock  phpunit.xml	storage

composer create-project downloads the Laravel starter app and its dependencies. On a fresh machine, composer global require laravel/installer then laravel new blog gives you an interactive setup with optional starter kits (React, Vue or Livewire, with authentication built in). New projects use SQLite by default, so there's no database server to set up.

Folder Holds
app/Models, app/Http/Controllers Your models and controllers
routes/web.php, routes/api.php URL routes
resources/views Blade templates
database/migrations Database schema changes, as PHP classes
.env Settings and secrets for this environment (never commit it)
artisan Laravel's command-line tool

Routes

Routes map URLs to code. The simplest return a value directly:

blog/routes/web.php
<?php

use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;

Route::get('/', fn () => 'Hello from Laravel!');

Route::get('/hello/{name}', fn (string $name) => "Hello, " . e($name) . "!")
    ->where('name', '[A-Za-z]+');

Route::get('/api/status', fn () => ['status' => 'ok', 'time' => '…']);

Route::resource('articles', ArticleController::class)->only(['index', 'store', 'show']);

A model, migration and controller

make:model -mc creates a model, its migration and a controller in one command:

bash
cd blog
php artisan make:model Article -mc --no-interaction | sed -E 's/\[[^]]*\]/[…]/; s/[0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{6}/YYYY_MM_DD_HHMMSS/'
Output
   INFO  Model […] created successfully.

   INFO  Migration […] created successfully.

   INFO  Controller […] created successfully.

Describe the table in the migration:

bash
cd blog
f=$(ls database/migrations/*_create_articles_table.php)
sed -i "s/\$table->id();/\$table->id();\n            \$table->string('title');\n            \$table->text('body');\n            \$table->boolean('published')->default(false);/" "$f"
sed -n '/Schema::create/,/});/p' "$f"
php artisan migrate --force 2>&1 | grep -E "create_articles|INFO" | sed -E 's/[0-9]{4}_[0-9]{2}_[0-9]{2}_[0-9]{6}/YYYY_MM_DD_HHMMSS/; s/[0-9.]+ms/…ms/; s/ \.+ / … /; s/ +$//'
Output
        Schema::create('articles', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->boolean('published')->default(false);
            $table->timestamps();
        });
   INFO  Running migrations.
  YYYY_MM_DD_HHMMSS_create_articles_table … …ms DONE

The model lists which fields may be filled from user input (mass assignment protection):

blog/app/Models/Article.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = ['title', 'body', 'published'];

    protected function casts(): array
    {
        return ['published' => 'boolean'];
    }

    public function scopePublished($query)
    {
        return $query->where('published', true);
    }
}

The controller uses validation and Eloquent:

blog/app/Http/Controllers/ArticleController.php
<?php

namespace App\Http\Controllers;

use App\Models\Article;
use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function index()
    {
        return Article::published()->latest('id')->get(['id', 'title']);
    }

    public function show(Article $article)       // route model binding: {article} → Article::findOrFail
    {
        return $article;
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'title' => ['required', 'string', 'max:100'],
            'body' => ['required', 'string'],
            'published' => ['boolean'],
        ]);
        return response()->json(Article::create($data), 201);
    }
}

Eloquent in Tinker

Tinker is an interactive console with your app loaded. Here it runs a script:

bash
cd blog
cat > /tmp/demo.php <<'PHP'
use App\Models\Article;
Article::create(['title' => 'Hello Laravel', 'body' => 'First post', 'published' => true]);
Article::create(['title' => 'Draft', 'body' => 'Not yet', 'published' => false]);
Article::create(['title' => 'Eloquent', 'body' => 'Rows become objects', 'published' => true]);
echo 'total: ', Article::count(), PHP_EOL;
echo 'published: ', Article::published()->pluck('title')->join(', '), PHP_EOL;
$a = Article::where('title', 'Draft')->first();
$a->update(['published' => true]);
echo 'now published: ', Article::published()->count(), PHP_EOL;
echo 'SQL: ', Article::published()->orderBy('id')->toRawSql(), PHP_EOL;
PHP
php artisan tinker --execute="$(cat /tmp/demo.php)"
Output
total: 3
published: Hello Laravel, Eloquent
now published: 3
SQL: select * from "articles" where "published" = 1 order by "id" asc

Article::create, where, pluck, update: no SQL written, but you can always see the SQL Eloquent generates.

Trying the routes

bash
cd blog
echo "APP_DEBUG=false" >> .env
(php artisan serve --port=8000 > /tmp/serve.log 2>&1 &)
for i in $(seq 1 20); do curl -s -o /dev/null http://127.0.0.1:8000 && break; sleep 1; done
curl -s http://127.0.0.1:8000/; echo
curl -s http://127.0.0.1:8000/hello/Asha; echo
curl -s -o /dev/null -w "/hello/123 → %{http_code}\n" http://127.0.0.1:8000/hello/123
curl -s http://127.0.0.1:8000/articles; echo
curl -s -H "Accept: application/json" http://127.0.0.1:8000/articles/1 | cut -c1-80; echo
curl -s -o /dev/null -w "/articles/99 → %{http_code}\n" http://127.0.0.1:8000/articles/99
pkill -f "artisan serve"; pkill -f "php -S" || true
Output
Hello from Laravel!
Hello, Asha!
/hello/123 → 404
[{"id":3,"title":"Eloquent"},{"id":2,"title":"Draft"},{"id":1,"title":"Hello Laravel"}]
{"id":1,"title":"Hello Laravel","body":"First post","published":true,"created_at

/articles/99 → 404
  • Returning an array or a model from a route gives a JSON response automatically.
  • {name} with ->where(...) only matches letters, so /hello/123 is a 404.
  • Route model binding turned /articles/1 into the Article with id 1, and /articles/99 into a 404 without any code from us.

Validation and CSRF

bash
cd blog
php artisan route:list --path=articles 2>/dev/null | grep -E "GET|POST" | sed -E 's/ +/ /g; s/^ //; s/ \.+ / /'
(php artisan serve --port=8000 > /tmp/serve.log 2>&1 &)
for i in $(seq 1 20); do curl -s -o /dev/null http://127.0.0.1:8000 && break; sleep 1; done
curl -s -o /dev/null -w "POST /articles without a CSRF token → %{http_code}\n" -d "title=Hi&body=x" http://127.0.0.1:8000/articles
pkill -f "artisan serve"; pkill -f "php -S" || true
cat > /tmp/v.php <<'PHP'
$v = Validator::make(
    ['title' => '', 'published' => 'maybe'],
    ['title' => ['required', 'string', 'max:100'], 'body' => ['required', 'string'], 'published' => ['boolean']],
);
echo json_encode($v->errors()->toArray(), JSON_PRETTY_PRINT), PHP_EOL;
PHP
php artisan tinker --execute="$(cat /tmp/v.php)"
Output
GET|HEAD articles articles.index › ArticleController@index
POST articles articles.store › ArticleController@store
GET|HEAD articles/{article} articles.show › ArticleController@show
POST /articles without a CSRF token → 419
{
    "title": [
        "The title field is required."
    ],
    "body": [
        "The body field is required."
    ],
    "published": [
        "The published field must be true or false."
    ]
}
  • Laravel protects every POST form route in routes/web.php against CSRF: a request without the session's token gets 419. Blade adds the token to your forms with @csrf. APIs live in routes/api.php (added with php artisan install:api) and use tokens instead of sessions.
  • When $request->validate([...]) fails, Laravel redirects back with these messages for a browser form, or returns a 422 response listing them for a JSON request. The rule names (required, max:100, boolean) read like a sentence, and there are about a hundred of them.

Blade templates

Blade is Laravel's template language. {{ }} prints a value and escapes it against XSS:

blade
{{-- resources/views/articles/index.blade.php --}}
@extends('layouts.app')

@section('content')
  <h1>Articles</h1>
  @forelse ($articles as $article)
    <h2><a href="{{ route('articles.show', $article) }}">{{ $article->title }}</a></h2>
  @empty
    <p>No articles yet.</p>
  @endforelse

  <form method="post" action="{{ route('articles.store') }}">
    @csrf
    <input name="title" value="{{ old('title') }}">
    @error('title') <p class="error">{{ $message }}</p> @enderror
    <button>Publish</button>
  </form>
@endsection

A controller returns it with return view('articles.index', ['articles' => $articles]);.

What else Laravel gives you

Feature Use
Starter kits (laravel new) Login, registration, password reset and profile pages, with React, Vue or Livewire
Eloquent relationships hasMany, belongsTo, belongsToMany, eager loading with with()
Queues and jobs Send emails or process uploads in the background
Mail and notifications Email, SMS and Slack messages
Scheduler Cron-like tasks defined in PHP
Testing Pest/PHPUnit with HTTP test helpers: $this->postJson('/articles', […])->assertStatus(201)
Deployment Laravel Cloud, Forge, or any PHP host with composer install --no-dev and php artisan migrate

The official documentation at laravel.com/docs and the free Laravel Bootcamp are the best next steps.

Practice

  1. Create a Laravel project and add a /about route that returns a Blade view.
  2. Make a Product model with a migration (name, price, stock) and seed three products with Tinker.
  3. Add a ProductController@index that returns products under a ?max_price= query parameter as JSON.
  4. Add validation to creating a product: name required, price numeric and greater than 0.
✎ Check your understanding

1.What does php artisan make:model Article -mc create?

2.What does {{ $title }} do in Blade?

3.What happens when $request->validate([...]) fails on an API request?

4.What is route model binding?

← Composer, autoloading and testing