Laravel 10 Tutorial
Welcome to the ultimate Laravel 10 tutorial. This guide will cover everything you need to know about Laravel 10, from setting up your development environment to building and deploying a robust application. We’ll start with numerous code samples to help you understand the practical aspects of Laravel 10 development.
Step 1: Installation and Setup
First, let’s set up our development environment for Laravel 10.
- Install Composer
- Download and install Composer from the official website: Composer.
- Verify Composer installation:
composer --version
- Create a New Laravel Project
- Use Composer to create a new Laravel project:
composer create-project --prefer-dist laravel/laravel blog
- Navigate to the project directory:
cd blog
- Start the development server:
php artisan serve
- Use Composer to create a new Laravel project:
Step 2: Basic Routing
Laravel 10 makes routing simple and elegant. Let’s define some basic routes.
- Defining Routes
- Open the
routes/web.php
file and add the following routes:// routes/web.php Route::get('/', function () { return view('welcome'); }); Route::get('/hello', function () { return 'Hello, World!'; });
- Open the
Step 3: Controllers
Controllers help organize your application logic. Let’s create a controller in Laravel 10.
- Create a Controller
- Use the Artisan CLI to generate a new controller:
php artisan make:controller PageController
- Add methods to your controller:
// app/Http/Controllers/PageController.php namespace App\Http\Controllers; use Illuminate\Http\Request; class PageController extends Controller { public function index() { return view('index'); } public function about() { return view('about'); } }
- Use the Artisan CLI to generate a new controller:
- Define Controller Routes
- Update your
web.php
file to use the controller:// routes/web.php use App\Http\Controllers\PageController; Route::get('/', [PageController::class, 'index']); Route::get('/about', [PageController::class, 'about']);
- Update your
Step 4: Views
Views handle the presentation logic in your application. Let’s create some basic views.
- Create Blade Templates
- Create a new
index.blade.php
file in theresources/views
directory:<!-- resources/views/index.blade.php --> <!DOCTYPE html> <html> <head> <title>Home Page</title> </head> <body> <h1>Welcome to Laravel 10</h1> </body> </html>
- Create an
about.blade.php
file:<!-- resources/views/about.blade.php --> <!DOCTYPE html> <html> <head> <title>About Us</title> </head> <body> <h1>About Us</h1> <p>This is the about page.</p> </body> </html>
- Create a new
Step 5: Database Configuration
Laravel 10 uses Eloquent ORM for database interactions. Let’s configure and use a database.
- Configure Database
- Update your
.env
file with your database credentials:DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD=secret
- Update your
- Create a Migration
- Generate a new migration file:
php artisan make:migration create_posts_table
- Define the table structure in the migration file:
// database/migrations/xxxx_xx_xx_xxxxxx_create_posts_table.php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreatePostsTable extends Migration { public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('posts'); } }
- Run the migration to create the table:
php artisan migrate
- Generate a new migration file:
Step 6: Eloquent ORM
Laravel’s Eloquent ORM provides a simple way to interact with your database. Let’s create a model and perform CRUD operations.
- Create a Model
- Generate a new Eloquent model:
php artisan make:model Post
- Define the model properties:
// app/Models/Post.php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Post extends Model { use HasFactory; protected $fillable = ['title', 'content']; }
- Generate a new Eloquent model:
- Perform CRUD Operations
- Create a new post:
// Create a new post $post = new Post; $post->title = 'First Post'; $post->content = 'This is the content of the first post.'; $post->save();
- Read a post:
// Read a post $post = Post::find(1); echo $post->title;
- Update a post:
// Update a post $post = Post::find(1); $post->title = 'Updated Title'; $post->save();
- Delete a post:
// Delete a post $post = Post::find(1); $post->delete();
- Create a new post:
Step 7: Authentication
Laravel 10 includes built-in authentication to make user management simple. Let’s set up authentication.
- Install Laravel UI
- Install the Laravel UI package:
composer require laravel/ui
- Generate the authentication scaffolding:
php artisan ui bootstrap --auth
- Install npm dependencies and compile assets:
npm install && npm run dev
- Install the Laravel UI package:
Step 8: Testing
Testing is an essential part of any application development. Let’s write some basic tests in Laravel 10.
- Write Tests
- Create a test file:
php artisan make:test ExampleTest
- Write a simple test:
// tests/Feature/ExampleTest.php namespace Tests\Feature; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; class ExampleTest extends TestCase { use RefreshDatabase; public function test_home_page() { $response = $this->get('/'); $response->assertStatus(200); $response->assertSee('Welcome to Laravel 10'); } }
- Create a test file:
- Run Tests
- Execute the tests using Artisan:
php artisan test
- Execute the tests using Artisan:
Step 9: Deployment
Deploying your Laravel application to a live server involves a few steps. Let’s go through them.
- Prepare for Deployment
- Set your environment to production:
php artisan config:cache php artisan route:cache php artisan view:cache
- Push your code to your repository and deploy using services like Laravel Forge, DigitalOcean, or AWS.
- Set your environment to production:
Conclusion
By following this tutorial, you have learned how to set up, develop, and deploy a Laravel 10 application. Continue exploring Laravel’s rich ecosystem to build more advanced features and applications. Happy coding!
Step 10: Advanced Routing
Laravel 10 offers advanced routing features that allow you to create complex and dynamic routes. Let’s explore some of these features.
- Route Parameters
- Define routes with parameters:
// routes/web.php Route::get('/user/{id}', function ($id) { return 'User '.$id; });
- Optional parameters:
// routes/web.php Route::get('/user/{name?}', function ($name = 'Guest') { return 'User '.$name; });
- Define routes with parameters:
- Named Routes
- Assign a name to a route:
// routes/web.php Route::get('/profile', function () { // ... })->name('profile');
- Generate URLs to named routes:
// Generating URLs $url = route('profile');
- Assign a name to a route:
- Route Groups
- Group routes under a common prefix:
// routes/web.php Route::prefix('admin')->group(function () { Route::get('/users', function () { // Matches the "/admin/users" URL }); });
- Group routes under a common prefix:
- Middleware
- Apply middleware to routes:
// routes/web.php Route::middleware(['auth'])->group(function () { Route::get('/dashboard', function () { // Uses Auth Middleware }); });
- Apply middleware to routes:
Step 11: Middleware
Middleware provides a convenient mechanism for filtering HTTP requests entering your application. Let’s create and use middleware in Laravel 10.
- Create Middleware
- Generate middleware using Artisan:
php artisan make:middleware CheckAge
- Define middleware logic:
// app/Http/Middleware/CheckAge.php namespace App\Http\Middleware; use Closure; class CheckAge { public function handle($request, Closure $next) { if ($request->age <= 200) { return redirect('home'); } return $next($request); } }
- Generate middleware using Artisan:
- Register Middleware
- Register middleware in the kernel:
// app/Http/Kernel.php protected $routeMiddleware = [ // ... 'check.age' => \App\Http\Middleware\CheckAge::class, ];
- Register middleware in the kernel:
- Use Middleware
- Apply middleware to routes:
// routes/web.php Route::get('/dashboard', function () { // Only accessible if age > 200 })->middleware('check.age');
- Apply middleware to routes:
Step 12: Blade Templates
Blade is the simple yet powerful templating engine provided with Laravel. Let’s dive deeper into Blade’s features.
- Blade Directives
- Conditionals:
<!-- resources/views/index.blade.php --> <h1>Welcome, {{ $user->name }}!</h1> @if($user->isAdmin()) <p>Admin Dashboard</p> @else <p>User Dashboard</p> @endif
- Loops:
<!-- resources/views/index.blade.php --> @foreach($tasks as $task) <li>{{ $task->name }}</li> @endforeach
- Conditionals:
- Components and Slots
- Create a reusable component:
<!-- resources/views/components/alert.blade.php --> <div class="alert alert-{{ $type }}"> {{ $slot }} </div>
- Use the component in a view:
<!-- resources/views/index.blade.php --> <x-alert type="success"> This is a success alert. </x-alert>
- Create a reusable component:
Step 13: Database Seeding
Database seeding provides a way to populate your database with test data. Let’s explore how to seed a database in Laravel 10.
- Create a Seeder
- Generate a seeder class:
php artisan make:seeder UsersTableSeeder
- Define seeder logic:
// database/seeders/UsersTableSeeder.php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; class UsersTableSeeder extends Seeder { public function run() { DB::table('users')->insert([ 'name' => 'Admin', 'email' => 'admin@example.com', 'password' => Hash::make('password'), ]); } }
- Generate a seeder class:
- Run the Seeder
- Call the seeder in the DatabaseSeeder:
// database/seeders/DatabaseSeeder.php namespace Database\Seeders; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { public function run() { $this->call(UsersTableSeeder::class); } }
- Execute the seeder:
php artisan db:seed
- Call the seeder in the DatabaseSeeder:
Step 14: File Storage
Laravel 10 provides a simple and elegant filesystem abstraction. Let’s learn how to manage file uploads and storage.
- Configure Filesystem
- Update the
config/filesystems.php
file to set up disk configurations.
- Update the
- File Upload
- Handle file uploads in a controller:
// app/Http/Controllers/FileController.php namespace App\Http\Controllers; use Illuminate\Http\Request; class FileController extends Controller { public function upload(Request $request) { if ($request->hasFile('file')) { $file = $request->file('file'); $path = $file->store('uploads'); return response()->json(['path' => $path], 200); } return response()->json(['error' => 'No file uploaded'], 400); } }
- Define a route for the file upload:
// routes/web.php use App\Http\Controllers\FileController; Route::post('/upload', [FileController::class, 'upload']);
- Create an upload form:
<!-- resources/views/upload.blade.php --> <form action="/upload" method="POST" enctype="multipart/form-data"> @csrf <input type="file" name="file"> <button type="submit">Upload</button> </form>
- Handle file uploads in a controller:
Step 15: API Development
Laravel 10 makes it easy to build RESTful APIs. Let’s create a simple API to manage posts.
- Create API Routes
- Define API routes in the
routes/api.php
file:// routes/api.php use App\Http\Controllers\Api\PostController; Route::get('/posts', [PostController::class, 'index']); Route::post('/posts', [PostController::class, 'store']); Route::get('/posts/{post}', [PostController::class, 'show']); Route::put('/posts/{post}', [PostController::class, 'update']); Route::delete('/posts/{post}', [PostController::class, 'destroy']);
- Define API routes in the
- Create API Controller
- Generate a controller for the API:
php artisan make:controller Api/PostController --api
- Implement the controller methods:
// app/Http/Controllers/Api/PostController.php namespace App\Http\Controllers\Api; use App\Http\Controllers\Controller; use App\Models\Post; use Illuminate\Http\Request; class PostController extends Controller { public function index() { return Post::all(); } public function store(Request $request) { $post = Post::create($request->all()); return response()->json($post, 201); } public function show(Post $post) { return $post; } public function update(Request $request, Post $post) { $post->update($request->all()); return response()->json($post, 200); } public function destroy(Post $post) { $post->delete(); return response()->json(null, 204); } }
- Generate a controller for the API:
Step 16: Testing API Endpoints
It’s important to test your API endpoints to ensure they work as expected. Let’s write some tests for our API.
- Write API Tests
- Create a test file:
php artisan make:test Api/PostTest
- Write test methods:
// tests/Feature/Api/PostTest.php namespace Tests\Feature\Api; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; use App\Models\Post; class PostTest extends TestCase { use RefreshDatabase; public function test_get_posts() { Post::factory()->count(3)->create(); $response = $this->getJson('/api/posts'); $response->assertStatus(200)->assertJsonCount(3); } public function test_create_post() { $postData = [ 'title' => 'New Post', 'content' => 'Content of the new post' ]; $response = $this->postJson('/api/posts', $postData); $response->assertStatus(201)->assertJsonFragment($postData); } public function test_update_post() { $post = Post::factory()->create(); $updateData = ['title' => 'Updated Title']; $response = $this->putJson("/api/posts/{$post->id}", $updateData); $response->assertStatus(200)->assertJsonFragment($updateData); } public function test_delete_post() { $post = Post::factory()->create(); $response = $this->deleteJson("/api/posts/{$post->id}"); $response->assertStatus(204); } }
- Create a test file:
- Run API Tests
- Execute the tests using Artisan:
php artisan test
- Execute the tests using Artisan:
Conclusion
This comprehensive Laravel 10 tutorial has covered a wide range of topics, from basic setup to advanced features like API development and testing. By following these steps, you can build, test, and deploy robust applications using Laravel 10. Continue exploring Laravel’s rich ecosystem to further enhance your skills and build even more powerful applications. Happy coding!