Unit 1 - Notes
Unit 1: Getting started with MVC Laravel framework
1. What is MVC Framework?
MVC (Model-View-Controller) is a software design pattern commonly used for developing user interfaces that divide the related program logic into three interconnected elements. This is done to separate internal representations of information from the ways information is presented to and accepted from the user.
The Three Components
-
Model (The Data Layer):
- Responsibility: Manages the data and logic of the application. It interacts with the database to retrieve, save, and update records.
- Behavior: It responds to requests for data from the view and instructions from the controller to update itself.
- Example: A
Userclass that defines what a user is and how to save a user to the SQL database.
-
View (The Presentation Layer):
- Responsibility: Handles the display of information to the user. It is what the user sees and interacts with (HTML/CSS).
- Behavior: It renders data from the Model into a form suitable for interaction. It contains no business logic.
- Example: An HTML page displaying a user's profile information.
-
Controller (The Application Logic Layer):
- Responsibility: Acts as an interface between Model and View components. It processes incoming requests, handles input, invokes Model changes, and selects the appropriate View for the response.
- Behavior: It accepts input and converts it to commands for the Model or View.
- Example: Receiving a
POSTrequest from a login form, validating the credentials via the Model, and redirecting the user to the Dashboard View.
MVC Workflow
- Request: The user interacts with the interface (View), sending a request (e.g., clicking a link).
- Routing: The request is intercepted by the Controller.
- Processing: The Controller accesses the Model to retrieve or update data.
- Response: The Controller passes the data to the View to be rendered and returned to the user.
Advantages of MVC
- Separation of Concerns: Distinct separation between logic and presentation makes code cleaner.
- Simultaneous Development: Developers can work on the core logic (Model/Controller) while designers work on the interface (View).
- Maintainability: Easier to debug and update specific parts of the application without affecting others.
2. Overview of Laravel Framework and its Features
Laravel is a free, open-source PHP web framework created by Taylor Otwell and intended for the development of web applications following the MVC architectural pattern. It is known for its elegant syntax and focus on developer happiness.
Key Features
-
Eloquent ORM (Object-Relational Mapping):
- Laravel includes a simple ActiveRecord implementation for working with databases. Each database table has a corresponding "Model" that is used to interact with that table.
- Benefit: Allows developers to issue database queries using PHP syntax rather than writing raw SQL.
-
Blade Templating Engine:
- A powerful, lightweight templating engine. Unlike other PHP templating engines, Blade does not restrict the use of plain PHP code in views.
- Benefit: Includes features like template inheritance (layouts) and sections to reduce code duplication.
-
Routing System:
- Laravel provides a very expressive method for defining routes. Routes are defined in the
routesdirectory (e.g.,web.php). - Benefit: Supports RESTful routing, route naming, and route parameters effortlessly.
- Laravel provides a very expressive method for defining routes. Routes are defined in the
-
Middleware:
- Provides a convenient mechanism for inspecting and filtering HTTP requests entering the application.
- Benefit: Commonly used for authentication (checking if a user is logged in before accessing a page) and CSRF protection.
-
Artisan Console:
- The built-in command-line interface.
- Benefit: Automates repetitive programming tasks (creating controllers, migrations, tests).
-
Database Migrations:
- Version control for the database schema.
- Benefit: Allows teams to modify and share the application's database schema easily without manually sharing SQL dumps.
-
Security:
- Takes care of application security by default.
- Benefit: Handles hashed passwords (Bcrypt), protects against SQL injection (via bindings), and prevents Cross-Site Request Forgery (CSRF) and Cross-Site Scripting (XSS).
3. Introduction to Composer
Composer is a dependency management tool for PHP. It allows you to declare the libraries your project depends on, and it will manage (install/update) them for you.
Core Concepts
- Dependency Management: Composer is not a package manager in the same sense as Yum or Apt. It deals with "packages" or libraries on a per-project basis, installing them in a directory (usually
vendor) inside your project. - composer.json: This file describes the dependencies of your project and may contain other metadata as well. It is the configuration file.
- composer.lock: This file locks the dependencies to specific versions. This ensures that every person working on the project has the exact same versions of the libraries installed.
- Packagist: The main repository for Composer. It aggregates public PHP packages installable with Composer.
4. Latest Composer Installation
To use Laravel, Composer must be installed on the development machine.
Prerequisites
- PHP installed on the system.
Installation on Windows
- Download the Composer-Setup.exe installer from the official getcomposer.org website.
- Run the installer. It will automatically find your
php.exefile. - Click Next through the wizard and Install.
- Open a new Command Prompt and type the following to verify:
BASHcomposer --version
Installation on macOS / Linux
- Open the terminal.
- Download the composer installer:
BASHphp -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" - Run the installer:
BASHphp composer-setup.php - Move the
composer.pharfile to a directory that is in your path (to make it global):
BASHsudo mv composer.phar /usr/local/bin/composer - Verify installation:
BASHcomposer --version
5. Latest Laravel Installation
There are two primary ways to create a new Laravel project: via the Laravel Installer or via Composer directly.
Prerequisites
- PHP (version >= 8.1 or 8.2 depending on the latest Laravel version).
- Composer installed.
- PHP Extensions enabled: BCMath, Ctype, Fileinfo, JSON, Mbstring, OpenSSL, PDO, Tokenizer, XML.
Method 1: Via Composer Create-Project (Recommended for beginners)
This command downloads the framework and installs all dependencies in one go.
- Open your terminal/command prompt.
- Navigate to the folder where you want to keep your projects (e.g.,
cd C:\xampp\htdocsorcd ~/Projects). - Run the following command:
BASHcomposer create-project laravel/laravel example-app
(Replaceexample-appwith your desired project name).
Method 2: The Global Installer
- Install the Laravel installer globally using Composer:
BASHcomposer global require laravel/installer - Create a new application:
BASHlaravel new example-app
Running the Application
Once installed, navigate into the project directory and start the local development server:
cd example-app
php artisan serve
The application will be accessible at
http://localhost:8000.
6. Directory/Application Structure
Understanding the directory structure is crucial for navigating a Laravel project.
Root Directories
- app/: Contains the core code of the application.
Http/Controllers: Where your Controllers live.Models: Where your Eloquent Models live (e.g., User.php).
- bootstrap/: Contains the
app.phpfile which bootstraps the framework. It also houses acachedirectory for performance optimization. - config/: Contains all of the application's configuration files (database, mail, app settings).
- database/: Contains database migrations, model factories, and seeds.
- public/: The entry point for all requests entering the application. Contains the
index.phpfile, images, JavaScript, and CSS assets. - resources/: Contains un-compiled assets such as pure CSS or SCSS, JavaScript, and most importantly, the views (Blade templates).
- routes/: Contains all logic for defining routes.
web.php: Routes for the web interface (includes session state and CSRF protection).api.php: Routes for APIs (stateless, token-based).
- storage/: Contains compiled Blade templates, file-based sessions, file caches, and other files generated by the framework.
- tests/: Contains automated tests (Unit and Feature tests).
- vendor/: Contains the Composer dependencies (libraries like Symfony, Guzzle, etc.). You do not edit files here.
Important Root Files
- .env: The environment configuration file. This holds sensitive data like database credentials (
DB_PASSWORD) and API keys. It is never committed to version control (Git). - composer.json: Defines the project dependencies.
- artisan: The script used to run Artisan commands.
7. Artisan
Artisan is the command-line interface included with Laravel. It provides a number of helpful commands for your use while developing your application.
Usage
Artisan is run from the root of the project directory via the terminal:
php artisan [command] [arguments]
Common Artisan Command Categories
1. General Commands
php artisan list: Lists all available commands.php artisan help [command]: Displays help screen for a specific command.php artisan serve: Starts the local development server.php artisan env: Displays the current environment (local, production, etc.).
2. Make Commands (Code Generation)
Used to generate files to save time on boilerplate code.
php artisan make:controller UserController: Creates a new Controller file.php artisan make:model Product: Creates a new Model.php artisan make:model Product -m: Creates a Model and a migration file for it.php artisan make:migration create_users_table: Creates a new database migration file.php artisan make:middleware CheckAge: Creates a new Middleware.
3. Database Commands
php artisan migrate: Runs pending migrations (updates the database schema).php artisan migrate:rollback: Rolls back the last database migration.php artisan db:seed: Seeds the database with records using seed classes.
4. Route Commands
php artisan route:list: Lists all registered routes in the application.
Artisan Tinker
php artisan tinker: Opens a REPL (Read-Eval-Print Loop). This allows you to interact with your entire Laravel application on the command line, including testing database queries via Eloquent models immediately without creating routes or controllers.