Laravel for Beginners: Routing, Controllers, Blade and Eloquent
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
| Term | What it means |
|---|---|
| Route | Maps a method and URL to code, defined in routes/web.php |
| Controller | A class whose methods handle requests |
| Blade | Laravel's template engine; {{ }} escapes output automatically |
| Eloquent | The ORM: each model class represents a database table |
| Migration | A PHP file describing a database schema change, kept in version control |
| Artisan | The command-line tool run with php artisan |
| Middleware | Code 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 serveOpen 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 andindex.phpfront 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 -mcDescribe 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() }}
@endsectionThe 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();| Command | Purpose |
|---|---|
| php artisan route:list | Show every route and its controller |
| php artisan make:controller Name | Create a controller class |
| php artisan make:migration name | Create an empty migration |
| php artisan migrate:rollback | Undo the last batch of migrations |
| php artisan tinker | Interactive shell for trying Eloquent queries |
| php artisan test | Run 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
@csrfthat displays validation errors beside each field. - Add a search box that filters products by name with an Eloquent
whereclause. - Commit your work with Git, keeping
.envout 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
.envfile, which exposes database passwords and the application key. - Using
{!! !!}for user content, which bypasses Blade escaping. - Leaving
$fillableunset 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.