Introduction
Laravel is a popular PHP framework known for its elegant syntax and powerful features for web development. Building a Laravel application involves setting up your development environment, creating and managing routes, controllers, views, and models, and testing and deploying your application. This guide will walk you through creating a basic Laravel application, covering everything from setup to execution. The tutorial is designed to be comprehensive and SEO-friendly.
Table of Contents
- Prerequisites
- Setting Up the Development Environment
- Creating a New Laravel Project
- Understanding the Laravel Project Structure
- Building the Application Components
- Managing Database Migrations and Seeders
- Handling User Input and Forms
- Fetching Data from the Database
- Styling the Application
- Testing Your Laravel Application
- Packaging and Deploying the Application
- Conclusion
Prerequisites
Before you start, make sure you have:
- Basic knowledge of PHP and web development concepts
- PHP (>= 7.3) installed
- Composer (PHP dependency manager) installed
- A web server like Apache or Nginx
- A database server like MySQL or SQLite
- A code editor or Integrated Development Environment (IDE) like PhpStorm or VS Code
Setting Up the Development Environment
- Install Laravel:
- Install Laravel using Composer:
bash composer global require laravel/installer
- Verify Installation:
- Ensure Laravel is installed correctly by checking the version:
bash laravel --version
Creating a New Laravel Project
- Create a New Laravel Project:
- Create a new Laravel project using the Laravel installer:
bash laravel new my_laravel_app
- Alternatively, you can use Composer to create the project:
bash composer create-project --prefer-dist laravel/laravel my_laravel_app
- Navigate to the Project Directory:
- Change to the project directory:
bash cd my_laravel_app
- Start the Development Server:
- Run the built-in Laravel development server:
bash php artisan serve
- Access your application in the browser at
http://localhost:8000
.
Understanding the Laravel Project Structure
A typical Laravel project structure includes:
app/
: Contains core application code (Controllers, Models, etc.).bootstrap/
: Contains files for bootstrapping the application.config/
: Contains configuration files.database/
: Contains migrations, seeders, and database factories.public/
: Contains the entry point for the application (index.php) and assets.resources/
: Contains views, raw assets, and language files.routes/
: Contains route definitions.storage/
: Contains logs, compiled views, and file uploads.tests/
: Contains test files.
Building the Application Components
- Define Routes:
- Open
routes/web.php
and define a basic route:
Route::get('/', function () {
return view('welcome');
});
- Create a Controller:
- Generate a new controller:
php artisan make:controller HelloController
- Define an action in
app/Http/Controllers/HelloController.php
:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class HelloController extends Controller
{
public function index()
{
return view('hello');
}
}
- Create a View:
- Create a new view file
resources/views/hello.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>Hello Page</title>
</head>
<body>
<h1>Hello, Laravel!</h1>
</body>
</html>
- Update Routes to Use Controller:
- Modify
routes/web.php
to use the new controller:php Route::get('/hello', [HelloController::class, 'index']);
Managing Database Migrations and Seeders
- Create a Migration:
- Generate a new migration:
bash php artisan make:migration create_users_table
- Define the table structure in
database/migrations/xxxx_xx_xx_create_users_table.php
:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
- Run Migrations:
- Apply the migrations to the database:
bash php artisan migrate
- Create a Seeder:
- Generate a new seeder:
bash php artisan make:seeder UsersTableSeeder
- Define seed data in
database/seeders/UsersTableSeeder.php
:
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
public function run()
{
DB::table('users')->insert([
'name' => 'John Doe',
'email' => 'john.doe@example.com',
'password' => Hash::make('password'),
]);
}
- Run Seeders:
- Seed the database with sample data:
bash php artisan db:seed --class=UsersTableSeeder
Handling User Input and Forms
- Create a Form:
- Create a form in
resources/views/form.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
</head>
<body>
<form action="/submit" method="POST">
@csrf
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<button type="submit">Submit</button>
</form>
</body>
</html>
- Handle Form Submission:
- Define a route and controller method for form submission in
routes/web.php
:Route::post('/submit', [HelloController::class, 'submit']);
- Implement the method in
app/Http/Controllers/HelloController.php
:
public function submit(Request $request)
{
$name = $request->input('name');
return "Submitted name: " . $name;
}
Fetching Data from the Database
- Create a Model:
- Generate a model:
bash php artisan make:model User
- Fetch Data Using Eloquent ORM:
- Fetch and display users in
app/Http/Controllers/HelloController.php
:
use App\Models\User;
public function showUsers()
{
$users = User::all();
return view('users', ['users' => $users]);
}
- Create a view
resources/views/users.blade.php
:
<!DOCTYPE html>
<html>
<head>
<title>Users</title>
</head>
<body>
<h1>Users</h1>
<ul>
@foreach ($users as $user)
<li>{{ $user->name }} ({{ $user->email }})</li>
@endforeach
</ul>
</body>
</html>
- Update Routes:
- Add a route for the users page in
routes/web.php
:php Route::get('/users', [HelloController::class, 'showUsers']);
Styling the Application
- Add CSS:
- Add custom styles in
public/css/style.css
and include it in your views:html <link rel="stylesheet" href="{{ asset('css/style.css') }}">
- Use Laravel Mix:
- Use Laravel Mix to compile assets. Define your styles and scripts in
webpack.mix.js
:
const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js')
.sass('resources/sass/app.scss', 'public/css');
- Run Laravel Mix:
npm install
npm run dev
Testing Your Laravel Application
- Write Unit Tests:
- Create test cases using PHPUnit. Generate a test file:
php artisan make:test UserTest
- Implement test methods in
tests/Feature/UserTest.php
:
use Illuminate\Foundation\Testing\RefreshDatabase;
class UserTest extends TestCase
{
use RefreshDatabase;
public function testUserCreation()
{
$response = $this->post('/submit', ['name' => 'John Doe']);
$response->assertSee('Submitted name: John Doe');
}
}
- Run Tests:
- Execute the tests from the command line:
bash php artisan test
Packaging and Deploying the Application
- Prepare for Deployment:
- Configure your
.env
file with production settings (database, mail, etc.).
- Deploy to a Server:
- Use tools like Laravel Forge or deploy manually to a server. Upload your project files, set up the web server, and configure the environment.
- Run Migration and Seed Commands:
- After deploying, run migrations and seeders on the server:
bash php artisan migrate php artisan db:seed
Conclusion
You’ve successfully built a basic Laravel application, covering essential aspects like project setup, routing, controllers, views, database management, form handling, and testing. By following these steps, you can develop, test, and deploy Laravel applications efficiently.
This guide provides a solid foundation for working with Laravel, and you can expand your application by exploring Laravel’s extensive features and capabilities.