Laravel is a powerful and elegant PHP framework designed to make web development a delightful and productive experience. Developed by Taylor Otwell, Laravel follows the MVC (Model-View-Controller) architectural pattern and is known for its expressive syntax and rich set of features. Whether you are building small projects or large enterprise applications, Laravel provides the tools and resources needed to bring your ideas to life efficiently.
Laravel 11, the latest version of this popular framework, introduces several new features and improvements that enhance performance, security, and developer experience. This guide will take you through the essentials of Laravel 11, from setting up your development environment to deploying your application. By the end of this guide, you will have a solid understanding of how to build robust and scalable web applications using Laravel 11.
Setting Up the Development Environment
To get started with Laravel 11, you need to set up your development environment. This includes installing PHP, Composer, and Laravel. PHP is the scripting language that Laravel is built on, while Composer is a dependency manager for PHP that Laravel uses to manage its packages.
Installing PHP, Composer, and Laravel
First, ensure that you have PHP installed on your system. Laravel 11 requires PHP 8.0 or later. You can download PHP from the official PHP website. After installing PHP, you need to install Composer. Download and run the Composer setup from the Composer website. Once Composer is installed, you can install Laravel globally by running the following command in your terminal:
composer global require laravel/installer
This command installs the Laravel installer globally on your system, allowing you to create new Laravel projects easily.
Setting Up a New Laravel Project
With Laravel installed, you can create a new project by running the following command:
laravel new my-laravel-app
This command creates a new Laravel project named my-laravel-app
. Navigate to the project directory and start the built-in development server:
cd my-laravel-app
php artisan serve
This will start the development server at http://localhost:8000
, and you can access your new Laravel application in your web browser.
Overview of Laravel Directory Structure
The Laravel directory structure is designed to keep your code organized and maintainable. Here is an overview of the main directories:
app
: Contains the core application code, including models, controllers, and middleware.config
: Contains configuration files for various aspects of the application.database
: Contains database migrations, seeders, and factories.resources
: Contains view templates, language files, and raw assets like CSS and JavaScript.routes
: Contains all route definitions for the application.public
: Contains the front controller and public assets like images, CSS, and JavaScript.
By understanding this directory structure, you can easily navigate and manage your Laravel projects.
Routing in Laravel
Routing is a fundamental aspect of Laravel, allowing you to define the URLs your application will respond to and the corresponding actions. Laravel routes are defined in the routes/web.php
file.
Basics of Routing
To define a simple route, open the routes/web.php
file and add the following code:
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
This route returns the welcome view, which is a simple HTML page typically located in the resources/views directory. Laravel’s view() function automatically looks for a file named welcome.blade.php in this directory and displays it when the route is accessed. This allows you to easily return views in response to web requests, making it straightforward to set up basic pages in your application.
Creating and Using Routes
You can create routes for different HTTP methods like GET, POST, PUT, and DELETE. Here is an example of defining routes for different actions:
Route::get('/about', function () {
return view('about');
});
Route::post('/contact', function () {
// Handle form submission
});
In this example, the first route responds to a GET request to the /about
URL and returns the about
view. The second route responds to a POST request to the /contact
URL and would contain logic to handle form submission.
Route Parameters and Middleware
Routes can also accept parameters, allowing you to create dynamic URLs. Here is an example of a route with a parameter:
Route::get('/user/{id}', function ($id) {
return "User ID: " . $id;
});
In this example, the route responds to a GET request to the /user/{id}
URL, where {id}
is a route parameter. The value of {id}
is passed to the route’s callback function, which returns a string containing the user ID.
You can also apply middleware to routes to handle tasks like authentication and logging. Middleware can be assigned to routes like this:
Route::get('/profile', function () {
// Only authenticated users may enter...
})->middleware('auth');
In this example, the route to the /profile
URL is protected by the auth
middleware, ensuring that only authenticated users can access it.
Controllers in Laravel
Controllers in Laravel help you organize your application logic by grouping related route actions. They are stored in the app/Http/Controllers
directory.
Introduction to Controllers
Controllers provide a convenient way to handle incoming requests and return responses. Instead of defining all your route logic in closure-based routes, you can move this logic to controller methods.
Creating and Using Controllers
To create a new controller, you can use the Artisan command-line tool. Run the following command to create a UserController
:
php artisan make:controller UserController
This command creates a new UserController
in the app/Http/Controllers
directory. You can then define methods within this controller to handle various actions. Here is an example:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function show($id)
{
return "User ID: " . $id;
}
}
In this example, the UserController
contains a show
method that accepts a user ID as a parameter and returns a string containing the user ID.
To use the UserController
in your routes, define a route in the routes/web.php
file. Here’s an example:
use App\Http\Controllers\UserController;
Route::get('/user/{id}', [UserController::class, 'show']);
This route maps to the show
method in the UserController
. When you visit a URL like /user/1
, Laravel calls the show
method and passes the id
parameter, which then returns “User ID: 1”.
Resource Controllers and Route Model Binding
Laravel also provides resource controllers to handle CRUD operations. You can create a resource controller using the following command:
php artisan make:controller UserController --resource
This command creates a controller with methods for standard CRUD operations. You can define resource routes in the routes/web.php
file like this:
Route::resource('users', UserController::class);
This will create routes for all CRUD operations (index, create, store, show, edit, update, and destroy) for the UserController
.
Route model binding in Laravel simplifies the process of accessing Eloquent models within your routes. It automatically converts route parameters into corresponding model instances, making your code cleaner and more readable. For example:
Route::get('/user/{user}', function (App\Models\User $user) {
return $user->name;
});
In this example, the {user}
parameter in the route is automatically resolved to an instance of App\Models\User
. This allows you to directly access the user’s properties, like name
, without needing to manually retrieve the model from the database. This feature reduces the amount of boilerplate code and improves the overall efficiency of your routes.
Blade Templating Engine
Blade is Laravel’s powerful templating engine that allows you to create dynamic and reusable views. Blade templates are stored in the resources/views
directory and use the .blade.php
file extension.
Introduction to Blade
Blade provides a simple and elegant syntax for writing templates, including support for template inheritance, components, and control structures.
Creating and Using Blade Templates
To create a Blade template, create a new file in the resources/views
directory. Here is an example of a simple Blade template named welcome.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Application</title>
</head>
<body>
<h1>Welcome to Laravel</h1>
</body>
</html>
This template defines a basic HTML structure with a title and a heading. You can render this template from a route or controller by using the view
function:
Route::get('/', function () {
return view('welcome');
});
This route returns the welcome
view when the root URL (/
) is accessed.
Blade Directives and Components
Directives
Blade provides several directives to help you write clean and maintainable templates. Here are some examples:
@if
: Conditional statements@foreach
: Looping through data@include
: Including other templates
Here is an example of using these directives:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Application</title>
</head>
<body>
<h1>Users</h1>
@if(isset($users) && count($users) > 0)
<ul>
@foreach($users as $user)
<li>{{ $user->name }}</li>
@endforeach
</ul>
@else
<p>No users found</p>
@endif
</body>
</html>
In this template, the @if
directive checks if there are any users. If there are, the @foreach
directive loops through each user and displays their name in a list item. If no users are found, a message is displayed instead.
To pass data from your controller to a view in Laravel, you can use the view()
function, which allows you to send data as an associative array. Here’s how you can pass a list of users from a controller to a view and display it using Blade directives:
In your controller, you might have something like this:
public function index()
{
$users = User::all();
return view('users.index', ['users' => $users]);
}
In this example, the index method retrieves all users from the database and passes them to the users.index view. Inside the Blade template, the users can be accessed through the $users variable, which is available because it was passed from the controller.
Components
Blade components in Laravel allow you to create reusable and modular pieces of UI, making it easier to maintain and scale your application. These components encapsulate both the logic and the view, promoting a clean and organized codebase.
To create a new component, you can use the Artisan command:
php artisan make:component Alert
Running this command generates two files: a component class in app/View/Components
and a corresponding Blade template in resources/views/components
. The component class handles any server-side logic, while the Blade template defines the HTML structure that will be rendered.
Define the Component Logic
Open app/View/Components/Alert.php
and define the properties and constructor. For example:
namespace App\View\Components;
use Closure;
use Illuminate\Contracts\View\View;
use Illuminate\View\Component;
class Alert extends Component
{
public function __construct(
public string $type,
public string $message
){}
public function render(): View|Closure|string
{
return view('components.alert');
}
}
Here, the component has type and message properties that will be passed to the view.
Create the Blade View
Open resources/views/components/alert.blade.php
and define the HTML structure. For example:
<div class="alert alert-{{ $type }}">
{{ $message }}
</div>
This Blade template uses the type and message properties to customize the alert’s styling and content.
Use the Component in Your Blade Templates
Once your component is created, you can easily include it in your Blade templates. For example, you might use the Alert component like this:
<x-alert type="danger" message="This is an error message" />
In this example, the Alert component is invoked with type and message attributes, allowing you to customize the appearance and content of the alert. The type attribute could control the styling (e.g., danger, success), while the message attribute displays the specific text. This approach not only makes your templates cleaner but also encourages reusability, as the same component can be used across different parts of your application with different data or styles.
Database and Eloquent ORM
Eloquent ORM is Laravel’s active record implementation, providing a simple and elegant way to interact with your database.
Introduction to Eloquent ORM
Eloquent makes it easy to work with databases by providing an intuitive and expressive syntax for querying and manipulating data. Models in Eloquent represent database tables, and each model instance corresponds to a row in the table.
Setting Up Database Configuration
To configure your database, update the .env
file with your database connection details:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
In this configuration, the database connection is set to MySQL, and the necessary credentials are provided.
Creating and Using Models, Migrations, and Seeders
Creating Models
Models in Laravel represent database tables and are used to interact with them. They allow you to perform operations like retrieving, inserting, updating, and deleting records. Models map to the database tables defined by migrations.
To create a model, use the Artisan command:
php artisan make:model ModelName
For instance, to create a model for a User table:
php artisan make:model User
This command creates a model class in the app/Models directory. By default, Laravel assumes the table name is the plural form of the model name, so User will map to the users table. You can customize this mapping by defining the $table
property in your model if the table name doesn’t follow Laravel’s naming convention.
Creating Migrations
Migrations define and modify the structure of your database tables. They help you version-control your database schema, making it easy to manage changes over time. Each migration file contains two methods: up for applying changes and down for reverting them.
To create a migration, use:
php artisan make:migration create_users_table
This command generates a migration file in the database/migrations
directory. Open the generated file and define the schema for your table. For example:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
In this migration, the users
table is created with columns for id
, name
, email
, password
, and timestamps. The up method specifies the columns for the users table, and the down method describes how to revert the changes by dropping the table. To run the migration and create the table, use the following command:
php artisan migrate
This command executes all pending migrations, creating or modifying tables in your database according to the schema defined in your migration files.
Creating Seeders
Seeders are used to populate your database with sample or default data. They help you quickly fill your tables with data for testing or initial setup.
To create a seeder, use:
php artisan make:seeder UserSeeder
This command creates a new seeder file in the database/seeders
directory. You can define the data to be inserted in the run
method of the seeder:
use Illuminate\Database\Seeder;
use App\Models\User;
class UserSeeder extends Seeder
{
public function run()
{
User::factory()->count(50)->create();
}
}
In this example, the UserSeeder
uses a factory to create 50 user records. To run the seeder and insert the data, use the following command:
php artisan db:seed --class=UserSeeder
Handling Forms and Validation
Forms are an essential part of any web application, allowing users to submit data to the server. Laravel makes handling forms and validation straightforward and intuitive.
Creating and Processing Forms
To create a form in Laravel, you can use the Blade templating engine. Here is an example of a simple form:
<form action="/submit" method="POST">
@csrf
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>
In this form, the @csrf
directive is used to include a CSRF token, which is necessary for form security in Laravel. The form submits data to the /submit
URL using the POST method.
Validation and Error Handling
Laravel provides a robust validation system that makes it easy to validate form data. Here is an example of handling form submission and validation in a controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FormController extends Controller
{
public function submit(Request $request)
{
$validatedData = $request->validate([
'name' => 'required|max:255',
]);
// Process the validated data
}
}
In this example, the submit
method in the FormController
validates the incoming request data against the specified rules. If validation fails, Laravel automatically redirects the user back to the form with error messages. If validation passes, the validatedData
array contains the validated data, which can then be processed as needed.
File Uploads
Laravel also makes handling file uploads simple. Here is an example of a form with a file upload field:
<form action="/upload" method="POST" enctype="multipart/form-data">
@csrf
<label for="file">Choose file:</label>
<input type="file" id="file" name="file">
<button type="submit">Upload</button>
</form>
This form includes a file input field and uses the enctype="multipart/form-data"
attribute to handle file uploads. In the controller, you can handle the file upload like this:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileController extends Controller
{
public function upload(Request $request)
{
$request->validate([
'file' => 'required|file|mimes:jpg,png,pdf|max:2048',
]);
$file = $request->file('file');
$path = $file->store('uploads');
return "File uploaded to: " . $path;
}
}
In this example, the upload
method validates the uploaded file against the specified rules. If the file is valid, it is stored in the uploads
directory using the store
method, and the file path is returned as a response.
Authentication and Authorization
Authentication and authorization are critical components of any web application. Laravel provides built-in features to handle these aspects efficiently.
Built-in Authentication Features
Laravel’s authentication system includes features like login, registration, password reset, and email verification. You can set up authentication quickly using Laravel’s authentication scaffolding:
composer require laravel/ui
php artisan ui vue --auth
npm install
npm run dev
php artisan migrate
These commands install the authentication scaffolding, set up the front-end dependencies, and run the necessary migrations to create the required database tables.
Customizing Authentication Logic
You can customize the authentication logic by modifying the Auth
controllers located in the app/Http/Controllers/Auth
directory. For example, you can add additional validation rules or redirect users to different pages after login. Here’s an example of customizing the registration controller:
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Foundation\Auth\RegistersUsers;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
class RegisterController extends Controller
{
use RegistersUsers;
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
}
In this example, the RegisterController
uses the RegistersUsers
trait to handle user registration. The validator
method defines the validation rules, and the create
method creates a new user with the validated data.
API Development with Laravel
Laravel makes it easy to develop APIs, providing tools for routing, controllers, and responses.
Setting Up API Routes and Controllers
API routes are defined in the routes/api.php file. Unlike previous Laravel versions, you’ll need to create this file by running the command php artisan install:api
. This command also installs Laravel Sanctum, which provides token-based authentication for your API.
Here’s an example of a basic API route:
use Illuminate\Http\Request;
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
In this example, the route responds to a GET request to the /user
URL and returns the authenticated user’s data when accessed with a valid Sanctum token. The route is protected by the auth:sanctum
middleware to ensure that only authenticated users can access it.
You can create API controllers using the Artisan command:
php artisan make:controller Api/UserController
This command creates a new controller in the app/Http/Controllers/Api
directory. You can define API methods in this controller to handle requests. Here is an example of a method to retrieve all users:
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function index()
{
return User::all();
}
}
In this example, the index
method retrieves all users from the database and returns them as a JSON response.
Using Laravel’s API Resources
Laravel’s API resources provide a way to transform your models into JSON responses. Here is an example of creating an API resource:
php artisan make:resource UserResource
This command creates a new resource class in the app/Http/Resources
directory. You can define the data transformation in the toArray
method:
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class UserResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
];
}
}
In this example, the UserResource
transforms the user model into a JSON response with the id
, name
, and email
attributes. You can use the resource in your controller to return a transformed JSON response:
use App\Http\Resources\UserResource;
use App\Models\User;
public function show(User $user)
{
return new UserResource($user);
}
In this example, the show
method returns a single user transformed by the UserResource
.
Implementing Authentication for APIs
Laravel supports API authentication using tokens with options like Laravel Passport or Sanctum. If you’ve installed API routes using php artisan install:api
, Sanctum is already set up.
Now, add the HasApiTokens
trait to your User
model:
namespace App\Models;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use HasApiTokens;
}
This trait provides methods to issue and manage API tokens. To protect your API routes, use the sanctum
middleware:
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
The /user
route is secured by the sanctum
middleware, ensuring that only authenticated users with valid API tokens can access it.
Testing in Laravel
Testing is an essential part of developing robust applications. Laravel provides built-in support for testing with PHPUnit.
Introduction to Testing
Laravel includes a testing suite that makes it easy to write and run tests. You can create tests using the Artisan command:
php artisan make:test ExampleTest
This command creates a new test class in the tests/Feature
directory. You can define test methods in this class to test various aspects of your application.
Writing Unit Tests and Feature Tests
Unit tests focus on testing individual components, while feature tests test the application’s functionality as a whole. Here is an example of a unit test:
namespace Tests\Unit;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
public function testBasicTest()
{
$this->assertTrue(true);
}
}
In this example, the testBasicTest
method asserts that true
is true, which is a simple example of a unit test.
Feature tests can interact with your application’s routes, controllers, and views. Here is an example of a feature test:
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function testHomePage()
{
$response = $this->get('/');
$response->assertStatus(200);
$response->assertSee('Welcome to Laravel');
}
}
In this example, the testHomePage
method sends a GET request to the root URL (/
) and asserts that the response status is 200 and the response body contains the text “Welcome to Laravel”.
Running Tests and Interpreting Results
To run your tests, use the following command:
php artisan test
This command runs all the tests in the tests
directory and displays the results in your terminal. By regularly running tests, you can ensure that your application behaves as expected and catch any regressions early.
Deploying Laravel Applications
Deploying Laravel applications involves preparing your application for production, configuring your server, and managing your application.
Preparing Your Application for Deployment
Before deploying your application, ensure that you have set up your environment variables correctly and optimized your application:
php artisan config:cache
php artisan route:cache
php artisan view:cache
These commands cache the configuration, routes, and views to improve performance in a production environment.
Deploying to Shared Hosting
If you are using shared hosting, you can deploy your application by uploading your files via FTP or using a deployment tool like Git. Ensure that your server meets the necessary requirements for running Laravel.
Using Laravel Forge and Envoyer
Laravel Forge and Envoyer provide powerful tools for deploying and managing Laravel applications. Forge automates server provisioning and configuration, while Envoyer handles zero-downtime deployments.
To deploy your application using Forge, follow these steps:
- Sign up for Laravel Forge.
- Connect your server provider (e.g., DigitalOcean, Linode).
- Create a new server and deploy your Laravel application.
Envoyer allows you to deploy updates to your application without downtime. To use Envoyer, follow these steps:
- Sign up for Envoyer.
- Create a new project and connect it to your repository.
- Set up deployment hooks to run necessary commands after each deployment.
Conclusion
In this article, we explored the fundamentals of Laravel 11, including setting up your development environment, routing, controllers, Blade templating, database interactions with Eloquent ORM, handling forms and validation, API development, testing, and deployment. We covered key concepts and provided code examples to help you understand and implement these features in your own projects.
Laravel is a robust and flexible framework with many additional features and tools that can help you build powerful web applications. We encourage you to explore more advanced topics, such as event broadcasting, queues, and job processing, to further enhance your Laravel skills.
Additional Resources for Learning Laravel
To continue your learning journey with Laravel, here are some additional resources that will help you expand your knowledge and skills:
- Laravel Documentation: The official documentation is a comprehensive resource for understanding the capabilities and usage of Laravel. Laravel Documentation
- Laracasts: A platform with high-quality video tutorials on Laravel and other web development topics. Laracasts
- Laravel News: A website with the latest news, tutorials, and packages related to Laravel. Laravel News
- Books: Books such as “Laravel: Up & Running” by Matt Stauffer provide in-depth insights and practical examples.
- Community and Forums: Join online communities and forums like the Laravel subreddit, Laracasts forums, and the Laravel Discord channel to connect with other Laravel developers, ask questions, and share knowledge.
- Sample Projects and Open Source: Explore sample projects and open-source Laravel applications on GitHub to see how others have implemented various features and functionalities.
By leveraging these resources and continuously practicing, you’ll become proficient in Laravel and be well on your way to developing impressive and functional web applications.