Code | Solutions

This laravel tutorial for beginners continues the Learn Laravel series with the part every request passes through first: Laravel routes, route parameters, and controllers. If you have not read it yet, start with Part 1: MVC, Artisan & how Laravel works — Part 2 uses the same Tasks app.

I’m Usman Nadeem, an AI Full Stack Developer based in Lahore with 12+ years of delivery since February 2014. The routing and controller patterns below are the same 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 route maps a URL and HTTP method to code, and a controller is the class that holds that code. Browser routes live in routes/web.php: Route::get('/about', ...) shows a page and Route::post('/tasks', ...) handles a form submit. Curly braces capture parts of the URL as route parameters, for example /tasks/{id}; {name?} makes one optional, and ->where('id', '[0-9]+') restricts it to numbers. Generate a controller with php artisan make:controller TaskController, point a route at it with [TaskController::class, 'show'], or register all seven CRUD routes with Route::resource('tasks', TaskController::class). The examples work on Laravel 12 and the current Laravel 13 release.

Watch the video

Prefer to watch first? Part 2 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 2 of this Laravel tutorial for beginners

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

  1. Laravel routes — how routes/web.php connects a URL to code, and when to use Route::get versus Route::post.
  2. Laravel route parameters — required {id}, optional {name?}, where() constraints, and named routes with the route() helper.
  3. Laravel controllers — php artisan make:controller, pointing a route at a controller method, and a resource controller that creates seven CRUD routes in one line.

You only need what Part 1 covered: a fresh Laravel project running with php artisan serve and a rough idea of MVC.


Laravel routes: the front door of your app

Every page in a Laravel app starts with a route. For anything a browser visits, routes are declared in routes/web.php. A route has three parts: the HTTP method, the URL, and the code to run when both match.

The two methods you will use first are:

  • Route::get — show something. Opening a page, clicking a link, or typing a URL in the address bar sends a GET request.
  • Route::post — receive something. Submitting a form (for example “Add task”) sends a POST request.

Here is the example from the video:

// routes/web.php
use Illuminate\Support\Facades\Route;

Route::get('/about', function () {
    return view('about');
});

Route::post('/tasks', function () {
    return 'Task saved!';
});

The first route says: when someone opens /about with GET, run this closure and return the about view (Laravel loads resources/views/about.blade.php). The second says: when a form POSTs to /tasks, return the text “Task saved!”. In a real app that closure would validate the input and create a Task — we will get there in the CRUD part of the series.

One security detail beginners trip over: POST, PUT, PATCH, and DELETE routes in web.php are protected against CSRF attacks. Your HTML form must include the token, or Laravel answers with a 419 Page Expired error:

<!-- resources/views/tasks/create.blade.php -->
<form method="POST" action="/tasks">
    @csrf
    <input type="text" name="title" placeholder="New task">
    <button type="submit">Add task</button>
</form>

Laravel also has shortcuts for routes that only return a view or a redirect, which keeps web.php tidy:

Route::view('/contact', 'contact');
Route::redirect('/home', '/tasks');

To see every route your app knows about, run:

php artisan route:list

That command is the fastest way to debug a “404 Not Found” — if the URL is not in the list, the route is missing or mistyped. Full details are in the official Laravel routing documentation.


Laravel route parameters: read data from the URL

Most real pages are not fixed URLs. Task 5 lives at /tasks/5, task 42 at /tasks/42. Instead of writing one route per task, you mark the changing part of the URL with curly braces. That is a route parameter, and Laravel passes its value into your function.

// routes/web.php
Route::get('/tasks/{id}', function (string $id) {
    return "Task #{$id}";
})->where('id', '[0-9]+')->name('tasks.show');

Route::get('/hello/{name?}', function (?string $name = 'Guest') {
    return "Hello, {$name}!";
});

Four ideas are packed into those few lines:

  • Required parameter {id}. Opening /tasks/5 runs the closure with $id = '5' and returns “Task #5”. Without a value (/tasks/), this route does not match.
  • Optional parameter {name?}. The question mark makes the segment optional, so you must give the PHP variable a default. /hello/Usman returns “Hello, Usman!” and /hello returns “Hello, Guest!”.
  • Constraint with where(). ->where('id', '[0-9]+') accepts digits only, so /tasks/abc returns a 404 instead of reaching your code. The shorthand ->whereNumber('id') does the same thing.
  • Named route with name(). ->name('tasks.show') gives the route a stable name you can use everywhere else in the app.

Why named routes matter

Once a route has a name, you generate its URL with the route() helper instead of hard-coding the path:

$url = route('tasks.show', ['id' => 5]);
// http://127.0.0.1:8000/tasks/5

return redirect()->route('tasks.show', ['id' => 5]);

And in a Blade view:

<a href="{{ route('tasks.show', ['id' => $task->id]) }}">View task</a>

If you later change the URL from /tasks/{id} to /my-tasks/{id}, every link built with route('tasks.show', ...) updates automatically. Nothing breaks. That is why I name almost every route in client projects, even small ones.


Laravel controllers: move the logic out of the routes file

Closures are fine for a two-line demo, but a real web.php full of database queries and validation becomes unreadable fast. A Laravel controller is a class that groups related request-handling methods — everything about tasks goes in TaskController — while the routes file only says which URL calls which method.

Generate the controller with Artisan (the same command from Part 1):

php artisan make:controller TaskController

Typical output:

   INFO  Controller [app/Http/Controllers/TaskController.php] created successfully.

Then move the logic from the closure into a show method:

// app/Http/Controllers/TaskController.php
namespace App\Http\Controllers;

class TaskController extends Controller
{
    public function show(string $id)
    {
        return "Task #{$id}";
    }
}

And point the route at that method using the array syntax [Controller::class, 'method']:

// routes/web.php
use App\Http\Controllers\TaskController;

Route::get('/tasks/{id}', [TaskController::class, 'show'])
    ->whereNumber('id')
    ->name('tasks.show');

The route parameter {id} is passed into show(string $id) by name, exactly like it was passed into the closure. The behaviour is identical; the code is now organized. Once you connect the Task model from Part 1, show can load the real record:

use App\Models\Task;

public function show(string $id)
{
    $task = Task::findOrFail($id); // 404 if the task does not exist
    return view('tasks.show', compact('task'));
}

Resource controllers: 7 CRUD routes in one line

Most features need the same seven actions: list, show a create form, save, show one, show an edit form, update, and delete. Laravel calls this a resource controller. Generate it with every method stubbed out:

php artisan make:controller TaskController --resource

Then register all the routes with a single line:

// routes/web.php
use App\Http\Controllers\TaskController;

Route::resource('tasks', TaskController::class);

That one line creates these routes (check with php artisan route:list):

MethodURLController methodRoute name
GET/tasksindextasks.index
GET/tasks/createcreatetasks.create
POST/tasksstoretasks.store
GET/tasks/{task}showtasks.show
GET/tasks/{task}/editedittasks.edit
PUT/PATCH/tasks/{task}updatetasks.update
DELETE/tasks/{task}destroytasks.destroy

Use either the explicit tasks.show route or Route::resource — not both — otherwise you register the same route name twice. Notice the resource routes use {task} instead of {id}; that enables route model binding, where Laravel loads the Task for you. We will use it when we build full CRUD. The official reference is the Laravel controllers documentation.


Recap: Laravel tutorial for beginners, Part 2

  1. Routes connect URLs to code. Declare them in routes/web.php: Route::get to show pages, Route::post to handle forms (with @csrf).
  2. Route parameters read data from the URL. {id} is required, {name?} is optional, where() or whereNumber() restricts the value, and name() plus route() keeps links from breaking.
  3. Controllers keep logic organized. php artisan make:controller TaskController, then [TaskController::class, 'show'] in the route — or Route::resource for all seven CRUD routes.

If you can open /tasks/5 and see “Task #5” coming from TaskController@show, you have finished Part 2.


What’s next: Part 3 — Blade Views, Layouts, and Components

So far the controller returns plain text. In Part 3 of this Laravel tutorial for beginners, the controller returns real pages:

  • Blade views — printing data with {{ $task->title }}, plus @if and @foreach
  • Layouts — one shared header and footer with @extends/@yield or a <x-layout> component
  • Blade components — reusable pieces such as a task card or a button

Follow Coding Solutions by Usman on YouTube, Instagram, or TikTok so you do not miss it. Missed the start? Read Laravel Tutorial for Beginners, Part 1. If you are heading toward APIs after the fundamentals, see Getting Started with Laravel: Your First RESTful API, where the same route and controller ideas return JSON.


Need help building a Laravel application?

If this laravel tutorial for beginners has you planning a production Laravel app — a new build, a feature, or a refactor — I take on selected Laravel development projects. Still choosing a stack? Read Laravel vs Node.js for SaaS, then send a short brief through the contact form and I will tell you whether I am a fit.


FAQ

Q1. What is a route in Laravel? A. A route maps an HTTP method and a URL to the code that should run. Browser routes are defined in routes/web.php, for example Route::get(‘/about’, …) to show the about page.

Q2. What is the difference between Route::get and Route::post? A. Route::get handles GET requests, which display a page when a user opens a URL or clicks a link. Route::post handles POST requests, which are sent when a form is submitted. POST routes in web.php need a CSRF token, added with @csrf inside the form.

Q3. How do route parameters work in Laravel? A. Wrap the changing part of the URL in curly braces, such as /tasks/{id}. Laravel passes the value into the route closure or controller method, so /tasks/5 gives $id the value 5. Add a question mark, as in {name?}, to make a parameter optional and give the PHP variable a default value.

Q4. How do I allow only numbers in a Laravel route parameter? A. Chain a constraint onto the route: where(‘id’, ‘[0-9]+’) or the shorthand whereNumber(‘id’). A URL such as /tasks/abc then returns a 404 instead of reaching your code.

Q5. What are named routes in Laravel? A. A named route has a label set with name(), such as tasks.show. You generate its URL with route(‘tasks.show’, [‘id’ => 5]), so if the path changes later, every link built with route() updates automatically.

Q6. How do I create a controller in Laravel 12? A. Run php artisan make:controller TaskController. Laravel creates app/Http/Controllers/TaskController.php. Add a method such as show, then point a route at it with Route::get(‘/tasks/{id}’, [TaskController::class, ‘show’]).

Q7. What is a resource controller in Laravel? A. A resource controller handles the seven standard CRUD actions: index, create, store, show, edit, update, and destroy. Generate it with php artisan make:controller TaskController –resource and register all seven routes with Route::resource(‘tasks’, TaskController::class).

Q8. What will Part 3 of this Laravel series cover? A. Part 3 covers Blade views, layouts, and components — how a controller returns a real HTML page, how to share one layout across pages with @extends and @yield or an x-layout component, and how to build reusable Blade components.

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