Laravel is one of the most popular PHP frameworks, known for its elegant syntax and powerful features. In this tutorial, we'll walk through setting up your first Laravel project and understanding its core concepts.
Prerequisites
Before we begin, make sure you have:
- PHP 8.2 or higher installed
- Composer (PHP package manager)
- A code editor (VS Code, PHPStorm, etc.)
- Basic PHP knowledge
Installing Laravel
The easiest way to create a new Laravel project is using Composer:
composer create-project laravel/laravel my-first-app
cd my-first-app
Alternatively, you can use the Laravel installer:
composer global require laravel/installer
laravel new my-first-app
Project Structure
Let's explore the key directories in a Laravel project:
my-first-app/
├── app/ # Application code
│ ├── Http/
│ │ ├── Controllers/ # Request handlers
│ │ └── Middleware/ # Request filters
│ ├── Models/ # Database models
│ └── Services/ # Business logic
├── config/ # Configuration files
├── database/ # Migrations and seeds
├── public/ # Web server entry point
├── resources/ # Views, CSS, JS
│ └── views/ # Blade templates
├── routes/ # Route definitions
│ └── web.php # Web routes
└── storage/ # Logs, cache, uploads
Understanding MVC
Laravel follows the Model-View-Controller pattern:
- Model: Represents data and business logic
- View: Handles presentation (HTML/Blade templates)
- Controller: Processes requests and coordinates Model/View
Creating Your First Route
Open routes/web.php and add a simple route:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/hello', function () {
return 'Hello, World!';
});
Route::get('/greet/{name}', function ($name) {
return "Hello, {$name}!";
});
Start the development server:
php artisan serve
Visit http://localhost:8000/hello to see your route in action!
Creating a Controller
Controllers help organize your route logic. Generate one using Artisan:
php artisan make:controller PostController
This creates app/Http/Controllers/PostController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
$posts = [
['title' => 'First Post', 'content' => 'Hello World'],
['title' => 'Second Post', 'content' => 'Laravel is great'],
];
return view('posts.index', ['posts' => $posts]);
}
public function show($id)
{
// In a real app, fetch from database
return view('posts.show', ['id' => $id]);
}
}
Update your routes to use the controller:
use App\Http\Controllers\PostController;
Route::get('/posts', [PostController::class, 'index']);
Route::get('/posts/{id}', [PostController::class, 'show']);
Creating Views with Blade
Blade is Laravel's powerful templating engine. Create resources/views/posts/index.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>Blog Posts</title>
</head>
<body>
<h1>All Posts</h1>
@forelse($posts as $post)
<article>
<h2>{{ $post['title'] }}</h2>
<p>{{ $post['content'] }}</p>
</article>
@empty
<p>No posts found.</p>
@endforelse
</body>
</html>
Blade Directives
Blade provides helpful directives:
| Directive | Purpose |
|---|---|
{{ $var }} |
Echo escaped content |
{!! $var !!} |
Echo unescaped content |
@if / @else |
Conditionals |
@foreach |
Loops |
@include |
Include partial views |
@extends |
Extend layouts |
@yield |
Define sections |
Working with Layouts
Create a base layout resources/views/layouts/app.blade.php:
<!DOCTYPE html>
<html>
<head>
<title>@yield('title', 'My App')</title>
</head>
<body>
<nav>
<a href="/">Home</a>
<a href="/posts">Posts</a>
</nav>
<main>
@yield('content')
</main>
<footer>
<p>© {{ date('Y') }} My App</p>
</footer>
</body>
</html>
Use it in your views:
@extends('layouts.app')
@section('title', 'Blog Posts')
@section('content')
<h1>All Posts</h1>
@foreach($posts as $post)
<article>
<h2>{{ $post['title'] }}</h2>
<p>{{ $post['content'] }}</p>
</article>
@endforeach
@endsection
Database Basics
Configure your database in .env:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_app
DB_USERNAME=root
DB_PASSWORD=
Creating a Migration
php artisan make:migration create_posts_table
Edit the migration file:
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Run the migration:
php artisan migrate
Creating a Model
php artisan make:model Post
Now you can use Eloquent ORM:
use App\Models\Post;
// Create
$post = Post::create([
'title' => 'My Post',
'content' => 'Content here'
]);
// Read
$posts = Post::all();
$post = Post::find(1);
// Update
$post->update(['title' => 'Updated Title']);
// Delete
$post->delete();
Next Steps
Now that you understand the basics, explore:
- Form Handling - Request validation and CSRF protection
- Authentication - Laravel Breeze or Jetstream
- API Development - Building RESTful APIs
- Testing - PHPUnit and feature tests
- Deployment - Laravel Forge or manual deployment
Conclusion
Laravel provides an excellent foundation for building modern PHP applications. Its elegant syntax, powerful features, and extensive ecosystem make it a great choice for projects of any size.
Ready to dive deeper? Check out our other tutorials or the official Laravel documentation.