0% found this document useful (0 votes)
356 views15 pages

Laravel MVC Architecture Overview

The document discusses key topics to study about Laravel including: 1) Laravel's MVC architecture and components, 2) typical components of a Laravel package, and 3) Laravel's directory structure and routing mechanisms. It provides details on Laravel's MVC pattern, package components like service containers and facades, directory structure folders like app and resources, and routing using URIs and route parameters.

Uploaded by

Merlin Mathew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
356 views15 pages

Laravel MVC Architecture Overview

The document discusses key topics to study about Laravel including: 1) Laravel's MVC architecture and components, 2) typical components of a Laravel package, and 3) Laravel's directory structure and routing mechanisms. It provides details on Laravel's MVC pattern, package components like service containers and facades, directory structure folders like app and resources, and routing using URIs and route parameters.

Uploaded by

Merlin Mathew
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Laravel - Must study Topics

1. Laravel MVC Architecture – with diagram


2. Key components of a typical Laravel package
3. Directory structure of Laravel
4. Laravel’s Routing mechanisms.
5. Types of route model binding supported in Laravel
6. Explain the role of Resource controllers in Laravel
7. Methods associated with Laravel’s resource controllers
8. Laravel Views - Creating & Rendering Views, Passing Data to Views, Sharing Data
with All Views

1. MVC Architecture

Laravel is an open-source PHP framework, which is robust and easy to understand. It


follows a model-view-controller design pattern. Laravel reuses the existing
components of different frameworks which helps in creating a web application. The web
application thus designed is more structured and pragmatic.

Laravel uses the MVC architecture.

MVC is divided into three letters shown below:

o M: 'M' stands for Model. A model is a class that deals with a database. For example,
if we have users in an application then we will have users model that deals with a
database to query the table of users if we have users model, then we will also have
a users table.
o V: 'V' stands for View. A view is a class that deals with an HTML. Everything that
we can see on the application in the browser is the view or the representation.
o C: 'C' stands for Controller. A controller is the middle-man that deals with both
model and view. A controller is the class that retrieves the data from the model
and sends the data to the view class.
Features of Laravel

Laravel offers the following key features which makes it an ideal choice for designing
web applications –

1. The Model-View-Controller architectural pattern support


2. Object-oriented libraries
3. The command-line interface - Artisan is the Command Line Interface and a global
command-line tool for Laravel.
4. Laravel’s templating engine - Blade templating - Blade allows using inbuilt
lightweight templates to create class-based components that can be reused anywhere in
your PHP application.
5. Effective ORM and database management - The Laravel framework uses an ORM
(Object Relational Mapping) called Eloquent
6. Adequate support for effective unit testing
7. Routing in the Laravel framework - Every time a server receives a request, a
specific action is triggered to handle it. This process is known as routing.

2. Key Components of a Typical Laravel Package

1. Service Containers - They are powerful tools for managing class dependencies and
performing dependency injection.

2. Service Providers - These are classes that bootstrap and register services for your
package.

3. Facades - Facades provide a static interface to classes that are available in the service
container, making it easy to access your package's functionality.

4. Configuration Files: Laravel packages often include configuration files that users can
publish and modify according to their needs. These files might contain settings, API keys,
or other customizable options.

5. Migrations: If your package involves a database, migrations are used to create or


modify database tables. Users can run these migrations to set up the necessary database
structure.

6. Models: Models represent the data structure of your package. They interact with the
database tables defined by your migrations.

7. Controllers: Controllers handle the HTTP requests and responses related to your
package. They define the logic for processing requests and returning appropriate
responses.

8. Views: If your package generates any HTML or user interface components, views are
used to define the presentation layer. Users can customize or override these views.

9. Routes: Routes define the URLs and associated controllers or closures for handling
HTTP requests related to your package. These routes can be added to the user's
application.
10. Middleware: Middleware can be part of your package to filter HTTP requests
entering your application. It's a great way to modify the request or perform checks before
the request reaches the controller.

11. Commands: Laravel packages often include Artisan commands that users can run
from the command line to perform various tasks related to your package.

12. Tests: A well-structured Laravel package includes tests to ensure its reliability.
PHPUnit tests can be written to cover various aspects of your package's functionality.

These components work together to provide a modular, reusable, and configurable


package that integrates seamlessly with Laravel applications.

3. Directory structure of Laravel


➢ app Directory
➢ bootstrap Directory
➢ config Directory
➢ database Directory
➢ public Directory
➢ resources Directory
➢ routes Directory
➢ storage Directory

app Directory
• app – The app directory contains the core code of your application.
o Console – The Console directory contains all of your Artisan commands.
o Exceptions – The Exceptions directory contains your application’s exception
handler and is also a good place to place any exceptions thrown by your application.
o Http – The Http directory contains your controllers, middleware, and requests.
▪ Controllers – It contains all controller files.
▪ Middleware – It contains all middleware files.
o Models – The Models directory contains all of your Eloquent model classes.
o Providers – The Providers directory contains all of the service providers for your
application.

bootstrap Directory
• bootstrap – The bootstrap directory contains the app.php file which bootstraps the
framework.
o cache – The cache directory which contains framework generated files for
performance optimization such as the route and services cache files.

config Directory
• config – The config directory, as the name implies, contains all of your application’s
configuration files.

database Directory
• database – The database directory contains your database migrations, model factories,
and seeds. If you wish, you may also use this directory to hold an SQLite database.
o factories – It contains model factories.
o migrations – It contains migrations.
o seeders – It contains seeds.

public Directory
• public – The public directory contains the index.php file, which is the entry point for all
requests entering your application and configures autoloading. This directory also
houses your assets such as images, JavaScript, and CSS.

resources Directory
• resources – The resources directory contains your views as well as your raw, un-
compiled assets such as CSS or
JavaScript.
o css – It contains css.
o js – It contains js.
o lang – It contains language files.
o views – It contains all blade php files.

routes Directory
• channels.php – The channels.php file is where you may register all of the event
broadcasting channels that your application supports.
• console.php – The console.php file is where you may define all of your Closure based
console commands. Each Closure is bound to a command instance allowing a simple
approach to interacting with each command’s IO methods. Even though this file does
not define HTTP routes, it defines console based entry points (routes) into your
application.
• web.php – The web.php file contains routes that the RouteServiceProvider places in the
web middleware group, which provides session state, CSRF protection, and cookie
encryption. If your application does not offer a stateless, RESTful API, all of your routes
will most likely be defined in the web.php file.

storage Directory
• storage – The storage directory contains your compiled Blade templates, file based
sessions, file caches, and
other files generated by the framework.
• app – The app directory may be used to store any files generated by your application.
o public – The public directory may be used to store user-generated files, such as
profile avatars, that should be publicly accessible.
• framework – The framework directory is used to store framework generated files and
caches.
• logs – The logs directory contains your application’s log files.

4. Laravel Routing

In Laravel, all requests are mapped with the help of routes. Routing in Laravel allows
you to route all your application requests to their appropriate controller. The main and
primary routes in Laravel acknowledge and accept a URI (Uniform Resource Identifier)
along with a closure, given that it should have to be a simple and expressive way of
routing.

Routing in Laravel includes the following categories −

• Basic Routing
• Route parameters
• Named Routes

1. Basic Routing

All the application routes are registered within the app/routes.php file. This file tells
Laravel for the URIs it should respond to and the associated controller will give it a
particular call. The sample route for the welcome page can be seen as shown in the
screenshot given below −

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


return view('welcome');});

Example

Observe the following example to understand more about Routing


app/Http/routes.php

<?php
Route::get('/', function () {
return view('welcome');
});

resources/view/welcome.blade.php

<!DOCTYPE html> display: table-cell;


<html> vertical-align: middle;
<head> }
<title>Laravel</title> .content {
<link href = text-align: center;
"https://fonts.googleapis.com/css?family=Lato:100" display: inline-block;
rel = "stylesheet" }
type = "text/css"> .title {
font-size: 96px;
<style> }
html, body { </style>
height: 100%; </head>
}
body { <body>
margin: 0; <div class = "container">
padding: 0;
width: 100%; <div class = "content">
display: table; <div class = "title">Laravel 5.1</div>
font-weight: 100; </div>
font-family: 'Lato';
} </div>
.container { </body>
text-align: center; </html>
The routing mechanism is shown in the image given below −

Detailed steps of routing mechanism:

Step 1 − Initially, we should execute the root URL of the application.

Step 2 − Now, the executed URL should match with the appropriate method in
the route.php file. In the present case, it should match the method and the root (‘/’)
URL. This will execute the related function.
Step 3 − The function calls the template
file resources/views/welcome.blade.php. Next, the function calls the view() function
with argument ‘welcome’ without using the blade.php.

This will produce the HTML output as shown in the image below −

Another Example

2. Route Parameters

Sometimes in the web application, you may need to capture the parameters passed with
the URL. For this, you should modify the code in routes.php file.

You can capture the parameters in routes.php file in two ways as discussed here −

Required Parameters

These parameters are those which should be mandatorily captured for routing the web
application. For example, it is important to capture the user’s identification number
from the URL. This can be possible by defining route parameters as shown below –

Route parameters are encapsulated within {} (curly-braces) with alphabets inside.

Route::get('ID/{id}',function($id) {
echo 'ID: '.$id;
});

Optional Parameters
Sometimes developers can produce parameters as optional and it is possible with the
inclusion of ? after the parameter name in URL. It is important to keep the default value
mentioned as a parameter name. Look at the following example that shows how to
define an optional parameter −

Route::get('user/{name?}', function ($name = 'merlin') { return $name;});

The example above checks if the value matches to merlin and accordingly routes to the
defined URL.

Regular Expression Constraints


You may constrain the format of your route parameters using the where method on a
route instance. The where method accepts the name of the parameter and a regular
expression defining how the parameter should be constrained:
Route::get('user/{name}', function ($name) {
//
})->where ('name', '[A-Za-z]+');
Another one for specifying number id:
Route::get('user/{id}', function ($id) {
//
})->where('id', '[0-9]+');

3. Named Routes

Named routes allow the convenient generation of URLs or redirects for specific routes.
You may specify a name for a route by chaining the name method onto the route
definition:
Route::get('/user/profile', function () {
// ...
})->name('profile');

You may also specify route names for controller actions:

Route::get(
'/user/profile',
[UserProfileController::class, 'show']
)->name('profile');

The user controller will call for the function showProfile with parameter as profile.
The parameters use name method onto the route definition.
5. Route Model Binding

Laravel route model binding provides a convenient way to automatically inject the model
instances directly into your routes. When injecting a model ID to a route or controller
action, you will often query the database to retrieve the model that corresponds to that
ID. For example, instead of injecting a store ID, you can inject the entire stores model
instance that matches the given ID.

Example:

Route::get('stores/{id}', function($id) {
$stores = Store::find($id);
});

This allows you to define that a particular parameter name (e.g., ({stores}) will indicate
to the route resolver that it should look up an Eloquent record with that ID and then pass
it in as the parameter instead of just passing the ID.

There are two kinds of route model binding: implicit and explicit

Implicit Route Model Binding


The simplest way to use route model binding is to name your route parameter something
unique to that model (e.g., name it $store instead of $id), then typehint that parameter in
the closure/controller method and use the same variable name there.

Route::get('stores/{store}', function(Store $store){


return view('stores.show')->with('store', $store);
});

Explicit route model binding


Because the route parameter ({store}) is the same as the method parameter ($store), and
the method parameter is type hinted with a Conference model (Store $store), Laravel sees
this as a route model binding. Every time this route is visited, the application will assume
that whatever is passed into the URL in place of {store} is an ID that should be used to
look up a Store and then that resulting model instance will be passed into your closure or
controller method.

Custom Route Model Binding


To manually configure route model binding, add a line like the one in the following
example to the boot() method in App\Providers\RouteServiceProvider.

public function boot(Route $router)


{
// Just allows the parent's boot() method to still run
parent::boot($router);
// Perform the binding
$router->model('shop', Store::class);
}
You’ve now defined that whenever a route has a parameter in its definition named {shop},
the route resolver will return an instance of the Store class with the ID of that URL
parameter.

6. Resource Controllers

Resource controllers are a convenient way to handle common CRUD (create, read, update,
and delete) operations in Laravel. Laravel provides a set of pre-defined resource
controllers that you can use out of the box, or you can create your own custom resource
controllers.

Benefits of using resource controllers

There are a number of benefits to using resource controllers in Laravel, including:

Reduced development time: Resource controllers can help you to reduce development
time by providing a pre-built set of code for handling common CRUD operations.

Improved code organization: Resource controllers can help you to organize your code
more effectively by grouping related CRUD operations together.

More consistent code: Resource controllers can help you to write more consistent code
by following a standardized set of conventions.

Easier testing: Resource controllers can make it easier to test your code by providing a
clear and concise way to interact with your application's resources.

Creating a resource controller

To create a resource controller in Laravel, you can use the php artisan make:controller
Artisan command.

For example, to create a resource controller for the Post model, you would run the
following command:

php artisan make:controller PostController --resource

This will create a new file called PostController.php in the app/Http/Controllers


directory.

Using a resource controller

Once you have created a resource controller, you can register it with Laravel's routing
system. To do this, open the routes/web.php file and add the following route:

Route::resource('posts', 'PostController');

This route will map all of the resource controller's methods to the /posts URI.
7. Actions of Resource Controller
A resource controller provides us with a total of seven methods with different actions

These actions are:

• index
• create
• store
• show
• edit
• update
• destroy

Initializing the resource controller in our routing file:


We can initialize the resource controller routes by using the below snippet in our
route.php file, which is located in the routes folder of our Laravel project using the
below snippet, i.e.,

Route::resource(‘photos’, controllerName::class);

Let’s take a look at the seven actions that a resource controller provides to us:

1. Index Method
Route Name: controllerName.index

Request Method: GET

The pages of all the records are displayed using this method. If you have a product page,
for example, you will use the index method to retrieve all of the records and show
them in the view in the appropriate order.

2. Create Method
Route Name: controllerName.create

Request Method : GET

This method is used to display the form for creating the record in the table. For
example, if you have a product table, we will create a form for the user to use to enter
values for the products in the database, and then we will display that form to the user.

3. Store Method
Route Name: controllerName.store

Request Method: POST

This method is used to store the record in the table. For example, if you have a
product table, then insert values in the products table by sending the params in a POST
request in the route.
4. Edit Method
Route Name: controllerName.edit

Request Method: GET

This method is used to show the editing form for a specified resource. This function
takes the id as an argument. It can be the primary key or any unique key of the table.

5. Show Method
Route Name: controllerName.show

Request Method: GET

Used to show the results for the specified resource from the database.

6. Update Method
Route Name: controllerName.update

Request Method: PUT/PATCH

Now we use that method to update the specified resource. This method takes
arguments by following the PUT or PATCH as a request method followed by a unique id
of the record we want to update.

7. Destroy Method
Route Name: controllerName.delete

Request Method: DELETE

Whenever we create a record, we also want a method and route for deleting this record.
By using the destroy method of the resource controller, we can do the same. It takes the
id of the table as an identifier for which record you want to delete.

8. Views in Laravel

A view is a file containing a mix of PHP code, HTML markup, and Blade templates. These
templates contain placeholders for dynamic content and are used to define the structure
and layout of a web page. When a user requests the application, the view is rendered
and returned to the user's browser.

Creating a View

To create a view in Laravel, follow these steps:

1. Navigate to the resources/views directory in your Laravel project.


2. Create a new file with a .blade.php extension. This extension tells Laravel to use
the Blade template engine to parse the view.
3. In the view file, add the HTML, PHP, and/or Blade templates that define the
structure and layout of the page. You can use placeholders for dynamic content,
such as or .
4. Save the view file.
Here's an example of a simple view that displays a greeting:

Example:

<!-- resources/views/greeting.blade.php -->

<h1>Hello, !</h1>
In the above example, the $name is a placeholder for dynamic content. The value
of $name will be displayed in the view when it is rendered.

Rendering a View

View helper functions can be used to display a view in a Laravel application. This
function takes the name of the view as its first argument and an array of data as its
second argument.

Here's an example of how to render the greeting view:

Example:

// in a Laravel controller
return view('greeting', ['name' => 'Alex']);
This will display the greeting view with the $name variable set to "Alex".

You can also render a view from a route.

Example:

// in routes

Route::get('/greeting', function () {
return view('greeting', ['name' => 'Alex']);
});
The above code will display the greeting view when the user visits the /greeting route.

Passing Data To Views

As you saw in the previous examples, you may pass an array of data to views to make that
data available to the view:

return view('greetings', ['name' => 'Victoria']);

When passing information in this manner, the data should be an array with key / value
pairs. After providing data to a view, you can then access each value within your view
using the data's keys, such as <?php echo $name; ?>.

You can also use the with method to add individual pieces of data to the view.

return view('greeting')

->with('name', 'Victoria')
->with('occupation', 'Astronaut');

Sharing Data With All Views

1. Go to app/Providers/AppServiceProvider.php and add the below line after


namespace.

use Illuminate\Support\Facades\View;

2. Now, inside the boot() method of the AppServiceProvider.php, create the data you
want to display to all views in Laravel as shown below

<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use DB;
use Illuminate\Support\Facades\View;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
$categories=DB::table('categories')->get();
View::share('categories',$categories);
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
On the above code, you can use $data instead of $categories as shown below

View::share('data',$data);

where $data is a dynamic variable.

You might also like