Laravel


1.      Laravel: What, Why......................................................................................................................................................... 1

1.1.       Why choose Laravel: Pros and Cons............................................................................................................ 1

1.2.       Laravel Framework VS Core PHP................................................................................................................... 2

2.      Laravel Architecture....................................................................................................................................................... 3

3.      Set up a simple to do list with Laravel and SQLite......................................................................................... 5

3.1.       UML Diagram.......................................................................................................................................................... 6

3.2.       routes/web.php...................................................................................................................................................... 6

3.3.       app/Http/Controllers/TodoController.php.............................................................................................. 6

3.4.       app/Models/Todo.php....................................................................................................................................... 7

3.5.       resources/views/todos/index.blade.php................................................................................................... 7

3.6.       resources/views/layouts/app.blade.php.................................................................................................... 8

4.      References:......................................................................................................................................................................... 8

 

1.        Laravel: What, Why

Laravel is a free, open-source PHP web framework that is widely used for building modern web applications. Think of it as a comprehensive toolkit that provides developers with a structured and efficient way to create complex, scalable, and secure web applications.

1.1.         Why choose Laravel: Pros and Cons

Pros of Laravel

Cons of Laravel

Rapid Development

Learning Curve for Beginners

Elegant and Expressive Syntax

Performance Overhead

MVC Architecture

Frequent Updates

Robust Security Features

Resource-Heavy (for very small projects)

Eloquent ORM

Opinionated Nature

Blade Templating Engine

Limited Built-in Payment Gateway Support

Artisan Command-Line Interface (CLI)

Challenges with Legacy Systems

Active and Supportive Community

 

 

Scalability

 

 

Excellent Documentation

 

 

Unit Testing Support

 

 

API Development

 

 

 

1.2.         Laravel Framework VS Core PHP

Feature

Laravel

Core PHP

Structure

An MVC structure

A modular structure

Code reusability

Beats this with code reusability

A faster development process

Flexibility

Strict development rules

Enhanced code flexibility

Caching

Facilitates cache back ends with multiple configurations

No caching mechanism

External dependency

External dependencies exist

No external dependencies

Security

Default authorization and authentication systems

Needs security rules to be integrated during development

Data communication

Data communication is authorized with security token

No default data communication authorization

Error and exception handling

Error and exception handling protocols are already configured

Does not support default error and exception handling facilities

Routing

Buit-in routing system

Manual routing setup

Templating Engine

Blade templating engine

No built-in templating engine

Database Access

Object-Relational Mapping (ORM)

Manual database querying

Testing

Robust testing suite (PHPUnit)

Limited testing support

Community

Large Laravel community with many resources and support

Large PHP developer community, but no specific Core PHP community

Scalability

Suitable for large-scale projects

Suitable for small to medium-sized projects

Learning Curve

An easier learning curve, with more approachable syntax

Steep learning curve, requires in-depth knowledge of PHP

 

2.        Laravel Architecture

graphic
1. Request:

This is the initial input, representing a user's action or a system call that triggers the application's processing.


2. Routing (app/routing.php):

Function: Handles the incoming request based on its URL. It acts as the dispatcher, determining which part of the application should process the request.

 

3. Controller (app/controller):

Function: Once the request is routed, the Controller is responsible for handling the business logic. It "talks with the model to get the data object" and then "feeds [it] to the view." This means it orchestrates the interaction between the Model (for data) and the View (for presentation).

 

4. Model (app/model):

Function: "Sets and Gets data from database." The Model represents the data and the business logic related to that data. It interacts directly with the database, abstracting the database operations from the rest of the application. This often involves using an ORM (Object-Relational Mapper).

 

5. Query Builder:

Function: The diagram shows the Controller interacting with the Query Builder, which in turn interacts with the Database. This suggests that while the Model might handle high-level data operations, the Controller (or even the Model internally) can use the Query Builder for more specific or complex database queries. The Query Builder provides a convenient, fluent interface for building SQL queries.

 

6. Database:

Function: This is where all the application's data is stored and retrieved.

 

7. Migration:

Function: "Helps to create schema for database using schema builder." Migrations are like version control for your database. They allow you to easily modify and share the application's database schema.

 

8. Seeding:

Function: "Helps to populate testing data to database." Seeding allows you to populate your database with initial or test data, which is crucial for development and testing environments.

 

9. View (laravel/app/view):

Function: "Takes the ORM object which helps to get data from database." the View is responsible for presenting the data received from the Controller to the user. It doesn't directly take an ORM object to get data from the database; rather, it receives data (often in the form of objects) that has already been retrieved by the Model and processed by the Controller.

View Layers: The diagram further breaks down the View into <view>.blade.php and Main View File <layout>.blade.php. This illustrates Laravel's templating system (Blade):

<view>.blade.php: These are individual view files that contain the specific content for a particular page or component.

Main View File <layout>.blade.php: This is a master layout file that defines the common structure (e.g., header, footer, navigation) of your application. Individual view files extend this layout.

 

10. Response to User:

This is the final output, typically an HTML page or API response, sent back to the user after the application has processed the request and rendered the appropriate view.

 

3.        Set up a simple to do list with Laravel and SQLite

graphic

3.1.         UML Diagram

graphic

3.2.         routes/web.php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\TodoController;

 

Route::get('/', function () {

    return redirect()->route('todos.index');

});

 

Route::get('/todos', [TodoController::class, 'index'])->name('todos.index');

Route::post('/todos', [TodoController::class, 'store'])->name('todos.store');

Route::patch('/todos/{todo}', [TodoController::class, 'update'])->name('todos.update');

Route::delete('/todos/{todo}', [TodoController::class, 'destroy'])->name('todos.destroy');

 

3.3.         app/Http/Controllers/TodoController.php

namespace App\Http\Controllers;

 

use Illuminate\Http\Request;

use App\Models\Todo;

 

class TodoController extends Controller

{

    public function index()

    {

        $todos = Todo::all();

        return view('todos.index', compact('todos'));

    }

 

    public function store(Request $request)

    {

        $request->validate([

            'title' => 'required|string|max:255',

        ]);

        Todo::create(['title' => $request->title]);

        return redirect()->route('todos.index');

    }

 

    public function update(Request $request, Todo $todo)

    {

        $todo->update(['completed' => $request->has('completed')]);

        return redirect()->route('todos.index');

    }

 

    public function destroy(Todo $todo)

    {

        $todo->delete();

        return redirect()->route('todos.index');

    }

}

 

3.4.         app/Models/Todo.php

namespace App\Models;

 

use Illuminate\Database\Eloquent\Model;

 

class Todo extends Model

{

    protected $fillable = ['title', 'completed'];

}

 

3.5.         resources/views/todos/index.blade.php

@extends('layouts.app')

 

@section('content')

<div class="container mt-5">

    <h1 class="mb-4">Simple To-Do List</h1>

    <form action="{{ route('todos.store') }}" method="POST" class="mb-4">

        @csrf

        <div class="input-group">

            <input type="text" name="title" class="form-control" placeholder="Add new task..." required>

            <button class="btn btn-primary" type="submit">Add</button>

        </div>

    </form>

    <ul class="list-group">

        @forelse($todos as $todo)

            <li class="list-group-item d-flex justify-content-between align-items-center">

                <form action="{{ route('todos.update', $todo) }}" method="POST" class="d-inline">

                    @csrf

                    @method('PATCH')

                    <input type="checkbox" name="completed" onchange="this.form.submit()" {{ $todo->completed ? 'checked' : '' }}>

                    <span class="ms-2 {{ $todo->completed ? 'text-decoration-line-through' : '' }}">{{ $todo->title }}</span>

                </form>

                <form action="{{ route('todos.destroy', $todo) }}" method="POST" class="d-inline">

                    @csrf

                    @method('DELETE')

                    <button class="btn btn-danger btn-sm">Delete</button>

                </form>

            </li>

        @empty

            <li class="list-group-item">No tasks yet.</li>

        @endforelse

    </ul>

</div>

@endsection

 

3.6.         resources/views/layouts/app.blade.php

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Simple To-Do List</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

</head>

<body>

    @yield('content')

</body>

</html>

 

4.        References:

https://phppot.com/php/php-laravel-project-example/
https://tech.knolskape.com/10-quick-tips-to-get-better-at-laravel