Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

Laravel for Beginners: Routing, Controllers, Blade and Eloquent

5 min read Updated By the SkillNewton team

What is Laravel?

Laravel is a free, open-source PHP framework for building web applications and APIs using the Model-View-Controller pattern. It provides routing, controllers, the Blade template engine, the Eloquent ORM for databases, migrations, validation, authentication tools and the Artisan command-line tool, so you write application features instead of rebuilding common plumbing.

Key Laravel terms

TermWhat it means
RouteMaps a method and URL to code, defined in routes/web.php
ControllerA class whose methods handle requests
BladeLaravel's template engine; {{ }} escapes output automatically
EloquentThe ORM: each model class represents a database table
MigrationA PHP file describing a database schema change, kept in version control
ArtisanThe command-line tool run with php artisan
MiddlewareCode that runs before a controller, such as login checks

Laravel builds on ideas covered in the PHP MVC guide and the object-oriented PHP guide; read those first if namespaces and classes still feel unfamiliar.

Installing Laravel with Composer

You need a supported PHP version, the PHP extensions listed in the Laravel documentation and Composer. Check the official documentation for the requirements of the current version, then create a project:

composer create-project laravel/laravel shop
cd shop
php artisan serve

Open http://127.0.0.1:8000 to see the welcome page. Database settings live in the .env file, which holds secrets and must never be committed to Git. Review the DB_ values there, then run php artisan migrate to create the default tables.

  • app/: models, controllers and other application classes.
  • routes/web.php: browser routes.
  • resources/views/: Blade templates.
  • database/migrations/: schema changes.
  • public/: the web root and index.php front controller.

Routes, migrations, models and controllers in one feature

Generate a model with its migration and controller in one Artisan command:

php artisan make:model Product -mc

Describe the table in the new migration, then run php artisan migrate:

// database/migrations/xxxx_xx_xx_create_products_table.php
public function up(): void
{
    Schema::create('products', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->unsignedInteger('price_paise');
        $table->text('description')->nullable();
        $table->timestamps();
    });
}

Allow mass assignment of safe fields in the model, then write the controller and routes:

// app/Models/Product.php
class Product extends Model
{
    protected $fillable = ['name', 'price_paise', 'description'];
}

// app/Http/Controllers/ProductController.php
class ProductController extends Controller
{
    public function index()
    {
        return view('products.index', [
            'products' => Product::orderBy('name')->paginate(20),
        ]);
    }

    public function show(Product $product)
    {
        return view('products.show', ['product' => $product]);
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'        => ['required', 'string', 'max:120'],
            'price_paise' => ['required', 'integer', 'min:1'],
            'description' => ['nullable', 'string'],
        ]);
        $product = Product::create($data);
        return redirect()->route('products.show', $product);
    }
}

// routes/web.php
Route::get('/products', [ProductController::class, 'index'])->name('products.index');
Route::get('/products/{product}', [ProductController::class, 'show'])->name('products.show');
Route::post('/products', [ProductController::class, 'store'])->middleware('auth');

The Product $product parameter uses route model binding: Laravel loads the product whose ID is in the URL, or returns a 404 page. validate() redirects back with error messages when input fails the rules, and returns only the validated fields when it passes, so unexpected input never reaches create().

Each controller file also needs use statements for the classes it references, such as App\Models\Product and Illuminate\Http\Request; Artisan adds the basic ones for you. When a controller needs the full set of create, read, update and delete actions, php artisan make:controller ProductController --resource generates all seven methods and Route::resource('products', ProductController::class) registers matching routes in one line.

Blade templates

Blade files end in .blade.php. {{ $value }} escapes output against cross-site scripting; {!! $value !!} prints raw HTML and should be avoided with user data.

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

@section('content')
  <h1>Products</h1>
  @forelse ($products as $product)
    <p>
      <a href="{{ route('products.show', $product) }}">{{ $product->name }}</a>
      Rs {{ number_format($product->price_paise / 100, 2) }}
    </p>
  @empty
    <p>No products yet.</p>
  @endforelse
  {{ $products->links() }}
@endsection

The layout file resources/views/layouts/app.blade.php holds the shared HTML and marks the slot with @yield('content'). Every form that posts data must include @csrf, which adds the token Laravel checks automatically.

Eloquent queries and useful Artisan commands

$cheap   = Product::where('price_paise', '<', 50000)->orderBy('price_paise')->get();
$product = Product::findOrFail(5);
$product->update(['name' => 'Gel pen, blue']);
$product->delete();

// Load related rows in one extra query instead of one per product
$orders = Order::with('customer')->latest()->take(10)->get();
CommandPurpose
php artisan route:listShow every route and its controller
php artisan make:controller NameCreate a controller class
php artisan make:migration nameCreate an empty migration
php artisan migrate:rollbackUndo the last batch of migrations
php artisan tinkerInteractive shell for trying Eloquent queries
php artisan testRun the test suite

Eloquent relationships are methods on the model. A Customer model with public function orders() { return $this->hasMany(Order::class); } lets you write $customer->orders, and the Order model declares the reverse with belongsTo(Customer::class). Eloquent builds prepared statements for you, so values in where() are safely bound.

Practical exercise: a small product catalogue in Laravel

Create a new Laravel project on your machine and build the product feature above.

  • Create the migration, model and controller, and seed five products with php artisan tinker.
  • Build the index and show views using a shared layout.
  • Add a create form with @csrf that displays validation errors beside each field.
  • Add a search box that filters products by name with an Eloquent where clause.
  • Commit your work with Git, keeping .env out of the repository.

You are done when php artisan route:list shows your routes, an empty name shows a validation message, a missing product ID returns 404 and HTML typed into a product name appears as plain text. Laravel projects form part of the advanced PHP course.

Common mistakes

  • Committing the .env file, which exposes database passwords and the application key.
  • Using {!! !!} for user content, which bypasses Blade escaping.
  • Leaving $fillable unset or unguarding models, which allows mass assignment of fields such as an admin flag.
  • Editing a migration that has already run on a shared database instead of adding a new one.
  • Accessing relationships inside loops without eager loading, causing the N+1 query problem.
  • Putting business logic in route closures instead of controllers or service classes.

Frequently asked questions

Should I learn plain PHP before Laravel?

Yes. Laravel uses classes, namespaces, closures and Composer throughout. A grounding in plain PHP makes framework errors understandable instead of mysterious.

Which Laravel version should I learn?

Learn the current version listed in the official documentation. Core ideas such as routing, Blade, Eloquent and migrations carry over between releases, and the upgrade guide lists what changed.

Can Laravel build APIs?

Yes. Controllers can return arrays or Eloquent models, which Laravel converts to JSON, and API resource classes shape the output. The principles are covered in the REST API guide.

How does Laravel compare with CodeIgniter?

Both are MVC frameworks. CodeIgniter is smaller with fewer conventions, while Laravel includes more built-in features such as Eloquent, queues and a larger package ecosystem.

Want to Learn This Properly?

The Advanced PHP Web Development & Full-Stack Application Development (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.