Azwar's Blog

Getting Started with Laravel: Building Your First Web Application

December 20, 2024 (7mo ago)Laravel

Hi everyone! I'm Azwar, a WordPress and Laravel developer. In this guide, I'll walk you through getting started with Laravel, one of the most popular PHP frameworks for building robust web applications. Whether you're coming from WordPress development or starting fresh, Laravel offers powerful tools for creating scalable applications.

Getting Started with Laravel: Building Your First Web Application
Getting Started with Laravel: Building Your First Web Application

Laravel is a free, open-source PHP web framework designed to make the development process more enjoyable for developers by taking care of common tasks used in many web projects. It provides a rich set of features including authentication, routing, sessions, caching, and more.

Prerequisites

Before we begin, make sure you have the following installed:

  • PHP 8.1 or higher
  • Composer (PHP package manager)
  • Node.js and NPM (for frontend assets)
  • A code editor (VS Code recommended)

Step 1: Installing Laravel

First, let's install Laravel using Composer:

composer create-project laravel/laravel my-first-app cd my-first-app

Step 2: Setting Up Your Environment

Copy the environment file and configure your database:

cp .env.example .env php artisan key:generate

Edit the .env file to configure your database connection:

DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=my_first_app DB_USERNAME=root DB_PASSWORD=your_password

Step 3: Understanding Laravel's MVC Architecture

Laravel follows the Model-View-Controller (MVC) pattern:

Models

Models represent your database tables and handle data logic:

<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { protected $fillable = [ 'title', 'content', 'author_id' ]; public function author() { return $this->belongsTo(User::class, 'author_id'); } }

Controllers

Controllers handle the application logic and coordinate between models and views:

<?php namespace App\Http\Controllers; use App\Models\Post; use Illuminate\Http\Request; class PostController extends Controller { public function index() { $posts = Post::with('author')->latest()->paginate(10); return view('posts.index', compact('posts')); } public function show(Post $post) { return view('posts.show', compact('post')); } public function create() { return view('posts.create'); } public function store(Request $request) { $validated = $request->validate([ 'title' => 'required|max:255', 'content' => 'required' ]); $post = Post::create($validated); return redirect()->route('posts.show', $post); } }

Views

Views handle the presentation layer using Blade templating:

{{-- resources/views/posts/index.blade.php --}} @extends('layouts.app') @section('content') <div class="container"> <h1>Blog Posts</h1> @foreach($posts as $post) <article class="post-card"> <h2>{{ $post->title }}</h2> <p>By {{ $post->author->name }}</p> <p>{{ Str::limit($post->content, 200) }}</p> <a href="{{ route('posts.show', $post) }}">Read More</a> </article> @endforeach {{ $posts->links() }} </div> @endsection

Step 4: Creating Database Migrations

Laravel migrations allow you to define your database schema in code:

php artisan make:migration create_posts_table

Edit the migration file:

<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; return new class extends Migration { public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('content'); $table->foreignId('author_id')->constrained('users'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('posts'); } };

Run the migration:

php artisan migrate

Step 5: Setting Up Routes

Define your application routes in routes/web.php:

<?php use App\Http\Controllers\PostController; use Illuminate\Support\Facades\Route; Route::get('/', function () { return view('welcome'); }); Route::resource('posts', PostController::class);

Step 6: Creating Forms with Laravel

Laravel provides powerful form helpers and validation:

{{-- resources/views/posts/create.blade.php --}} @extends('layouts.app') @section('content') <div class="container"> <h1>Create New Post</h1> <form action="{{ route('posts.store') }}" method="POST"> @csrf <div class="form-group"> <label for="title">Title</label> <input type="text" name="title" id="title" class="form-control @error('title') is-invalid @enderror" value="{{ old('title') }}"> @error('title') <div class="invalid-feedback">{{ $message }}</div> @enderror </div> <div class="form-group"> <label for="content">Content</label> <textarea name="content" id="content" class="form-control @error('content') is-invalid @enderror">{{ old('content') }}</textarea> @error('content') <div class="invalid-feedback">{{ $message }}</div> @enderror </div> <button type="submit" class="btn btn-primary">Create Post</button> </form> </div> @endsection

Step 7: Authentication with Laravel

Laravel makes authentication simple with built-in features:

composer require laravel/ui php artisan ui bootstrap --auth npm install && npm run dev

Step 8: Working with Eloquent ORM

Laravel's Eloquent ORM provides an elegant way to work with your database:

// Creating records $post = Post::create([ 'title' => 'My First Post', 'content' => 'This is the content of my first post.' ]); // Querying records $recentPosts = Post::where('created_at', '>=', now()->subDays(7))->get(); // Relationships $user = User::find(1); $userPosts = $user->posts; // Assuming User has many posts // Eager loading to prevent N+1 queries $posts = Post::with('author')->get();

Step 9: Adding Middleware

Middleware provides a mechanism for filtering HTTP requests:

// Create middleware php artisan make:middleware AdminMiddleware // Apply to routes Route::middleware(['auth', 'admin'])->group(function () { Route::get('/admin', [AdminController::class, 'index']); });

Best Practices for Laravel Development

  1. Follow Laravel Conventions: Use naming conventions for models, controllers, and routes
  2. Use Eloquent Relationships: Leverage Laravel's powerful relationship features
  3. Implement Proper Validation: Always validate user input
  4. Use Laravel's Built-in Features: Take advantage of authentication, caching, and queues
  5. Write Tests: Laravel makes testing easy with PHPUnit
  6. Optimize Database Queries: Use eager loading and query optimization

Running Your Application

Start the development server:

php artisan serve

Your application will be available at http://localhost:8000.

Conclusion

Laravel provides a robust foundation for building modern web applications. Its elegant syntax, powerful features, and comprehensive documentation make it an excellent choice for both beginners and experienced developers.

As you continue your Laravel journey, explore features like:

  • Artisan Commands for automation
  • Queues for background job processing
  • Events and Listeners for decoupled code
  • API Resources for building RESTful APIs
  • Blade Components for reusable UI elements

Additional Resources

Comments