CST463 · S7 CSE

Laravel and the MVC framework

Exam notes on MVC architecture, Laravel routing, controllers, models and views.

Module 5 Back to CST463 hub

Source: laravel_notes.docx — course material by Kiran V.K., published here so it is readable without a Google account.

MVC Architecture Overview

Laravel Overview

Laravel is a web application framework with expressive, elegant syntax. It provides a rich set of functionalities that incorporates many features of MVC. Laravel aims to make development tasks easier by reducing common tasks used in most web projects, such as routing, templating, caching, and authentication.

Laravel MVC Framework

Resource Controllers in Laravel

A resource controller in Laravel is a special controller that handles all HTTP requests for a specific resource (like articles, profiles) following RESTful conventions. It provides methods for CRUD operations: create, read, update, delete, and more.

Laravel's Routing Mechanisms

Routing in Laravel deals with directing HTTP requests to their appropriate controllers. Routes are defined in the 'routes' folder. Laravel supports basic routing, route parameters, named routes, middleware, and resource controllers.

Understanding Routes, Controllers, and Models in Laravel

Routes in Laravel

Routes are the invocation URLs that users interact with. Defined in the routes files (such as web.php), they serve as the entry points for HTTP requests. Each route is mapped to a specific controller action, determining which controller method is executed for a given URL.

Example: A route definition in web.php

php

Route::get('/posts', 'PostController@index');

This defines a route for '/posts' that is handled by the 'index' method of 'PostController'.

Route::get('/posts/{post}', 'PostController@show');

displays a single post based on its ID.

Controllers in Laravel

Controllers contain the application's logic. They are responsible for processing user requests, interacting with model classes for data handling, and preparing responses. This response could be a rendered view, a JSON response, a redirect, or other types of HTTP responses.

Example: A controller method in PostController

php

class PostController extends Controller
{
    public function index()
    {
        $posts = Post::all();
        return view('posts.index', compact('posts'));
    }
}

Model Classes in Laravel

Models represent the application's data and are directly mapped to database tables, typically with one model class per table. Using Eloquent, Laravel’s ORM, models simplify database interactions through an object-oriented approach. They also encapsulate business logic related to data, such as validation and relationships.

Understanding Eloquent ORM Model-to-Table Mapping in Laravel

Naming Convention

php

By default, Eloquent uses a naming convention to determine the database table associated with a model. For a model named 'Post', it assumes the database table is named 'posts'. This is based on the simple pluralization of the model name.

Example of Custom Table Name:

class Post extends Model
{
    protected $table = 'my_custom_posts';
}

In this example, Eloquent will use 'my_custom_posts' as the table associated with the 'Post' model.

Primary Key

php

Eloquent assumes each table has a primary key column named 'id'. If your table uses a different column name or type for its primary key, you can define it in your model.

Example of Custom Primary Key:

protected $primaryKey = 'post_id';

This tells Eloquent to use 'post_id' as the primary key for the 'Post' model.

Timestamps

php

By default, Eloquent expects 'created_at' and 'updated_at' timestamp columns in your table. If your table doesn't have these timestamp columns, you can disable this feature.

Example of Disabling Timestamps:

public $timestamps = false;

Model Properties and Methods

Models in Laravel can define relationships, scopes, accessors, mutators, and more. Example of a Basic Eloquent Model:

class Post extends Model

php

{
    protected $table = 'posts';
    protected $primaryKey = 'post_id';
    public $timestamps = false;
}

This model is set up to interact with a database table named 'posts', with a custom primary key and no automatic timestamp management.

Route Model Binding in Laravel

Creating & Rendering Views

Views in Laravel are created using the Blade templating engine, stored in the 'resources/views' directory. Blade allows you to embed PHP code in HTML templates, making it dynamic and interactive.

Passing Data to Views

Data can be passed to views using several methods, including with, compact, or directly as an array. Controllers typically handle data passing.

Sharing Data with All Views

Data can be shared across all views using view composers or view shares, useful for data required in multiple views like user information, settings, etc.

Example Use Case

Example: Basic Route Definition

Route::get('/posts', 'PostController@index'); Route::get('/posts/{post}', 'PostController@show'); This example shows two routes. The first route displays all posts, and the second displays a single post based on its ID.

Example: PostController Methods

// PostController

php

public function index()
{
    $posts = Post::all();
    return view('posts.index', compact('posts'));
}

public function show(Post $post)
{
    return view('posts.show', compact('post'));
}

These methods in PostController handle requests to list all posts (index) and to show a specific post (show). The show method uses route model binding.

Example: Blade View for Listing Posts

{{-- resources/views/posts/index.blade.php --}}

php

@extends('layouts.app')

@section('content')
<h1>All Posts</h1>
<ul>
        @foreach ($posts as $post)
<li>
<a href="{{ route('posts.show', $post->id) }}">
                    {{ $post->title }}
</a>
</li>
        @endforeach
</ul>
@endsection

This Blade view (index.blade.php) lists all blog posts. Each post title links to its detailed view.

Example: Blade View for Showing a Post

{{-- resources/views/posts/show.blade.php --}}

php

@extends('layouts.app')

@section('content')
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
<a href="{{ route('posts.index') }}">Back to All Posts</a>
@endsection

This Blade view (show.blade.php) displays the details of a single blog post.

Importance of Route Model Binding

Importance of Controller

Example: In our use case, PostController has methods like index and show, where index retrieves and displays all posts, while show deals with displaying a specific post.

Views in Laravel

Passing Data to Views

Sharing Data with All Views