Setting Up a Laravel Application

Module 19: PHP Backend - Laravel

Introduction

Setting up a Laravel application is like preparing a kitchen before cooking an elaborate meal - the time you invest in proper setup pays dividends throughout the development process. In this lecture, we'll walk through the process of installing Laravel and configuring your development environment.

Whether you're building a personal blog, an e-commerce platform, or a complex enterprise application, the initial setup process follows the same pattern, establishing a solid foundation for your project.

Prerequisites

Before installing Laravel, ensure your development environment meets these requirements:

Think of these prerequisites as the foundational tools in your workshop - you need the right tools of sufficient quality before you can begin crafting your application.

flowchart LR A[PHP 8.1+] --> F[Laravel] B[Composer] --> F C[Database] --> F D[Web Server] --> F E[Extensions] --> F

Installation Methods

Method 1: Composer Create-Project

The most straightforward way to create a new Laravel project is using Composer's create-project command:

composer create-project laravel/laravel example-app

This is like buying a pre-assembled furniture kit - it comes with all the standard pieces organized in the expected structure.

Method 2: Laravel Installer

For developers who frequently create Laravel projects, the Laravel installer is more convenient:


# Install the Laravel installer globally
composer global require laravel/installer

# Create a new project
laravel new example-app
            

This is similar to having a specialized tool that quickly and consistently creates new project structures - like a template cutter for woodworking that ensures precision every time.

Method 3: Using Docker with Laravel Sail

Laravel Sail provides a lightweight Docker environment for Laravel development:


# Create a new Laravel project
curl -s "https://laravel.build/example-app" | bash

# Navigate to the application directory
cd example-app

# Start the Docker containers
./vendor/bin/sail up
            

Using Sail is like working in a pre-configured workshop where all the tools are already set up and calibrated perfectly - you can focus entirely on building rather than environment setup.

Project Structure

A fresh Laravel installation has a well-organized directory structure. Understanding this structure is like knowing the floor plan of a building - it helps you navigate efficiently.

graph TD A[Laravel Project Root] --> B[app/] A --> C[bootstrap/] A --> D[config/] A --> E[database/] A --> F[public/] A --> G[resources/] A --> H[routes/] A --> I[storage/] A --> J[tests/] A --> K[vendor/] B --> B1[Console/] B --> B2[Exceptions/] B --> B3[Http/] B --> B4[Models/] B --> B5[Providers/] B3 --> B3a[Controllers/] B3 --> B3b[Middleware/] G --> G1[css/] G --> G2[js/] G --> G3[views/] H --> H1[api.php] H --> H2[web.php] H --> H3[console.php] H --> H4[channels.php]

Key Directories Explained

This organization follows separation of concerns principles, making it easier to maintain and scale your application.

Configuration Files

Laravel's configuration files reside in the config/ directory. Understanding these files is crucial for customizing your application's behavior.

Key Configuration Files

Configuration in Laravel is like setting up presets on a professional camera - you configure it once, and then you can focus on taking great photos without worrying about the technical settings.

Environment Configuration

Laravel uses a .env file to store environment-specific configuration. This is particularly important for keeping sensitive information like database credentials and API keys secure.


# Example .env file
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:abcdefghijklmnopqrstuvwxyz123456=
APP_DEBUG=true
APP_URL=http://localhost

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example_app
DB_USERNAME=root
DB_PASSWORD=password

MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
            

The .env file serves as a control panel for environment-specific settings, allowing the same codebase to run in different environments (development, staging, production) with appropriate configurations.

This approach is similar to how a theatrical production might have different lighting and sound settings for different venues - the play (your code) remains the same, but the environment settings adapt.

Setting Up the Database

Database configuration is a critical part of setting up a Laravel application. Laravel supports several database systems out of the box.

Database Configuration

Configure your database connection in the .env file:


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example_app
DB_USERNAME=root
DB_PASSWORD=password
            

Laravel will use these settings to connect to your database. It's like setting up the address and access credentials for your application's data warehouse.

Running Migrations

Laravel uses migrations to define and version your database schema. Think of migrations as a series of blueprints that progressively build and modify your database structure.


# Create a new migration
php artisan make:migration create_products_table

# Run migrations to build your database
php artisan migrate

# Roll back the last batch of migrations
php artisan migrate:rollback
            

This approach provides several benefits:

Using migrations is like having a time machine for your database - you can move forward to apply new changes or backward to undo them as needed.

Artisan Command Line Tool

Artisan is Laravel's command-line interface, providing numerous helpful commands for common tasks. It's like having a Swiss Army knife for Laravel development.

Common Artisan Commands


# List all available commands
php artisan list

# Display help for a specific command
php artisan help migrate

# Create a controller
php artisan make:controller ProductController

# Create a model with migration
php artisan make:model Product -m

# Clear configuration cache
php artisan config:clear

# Start the development server
php artisan serve
            

Artisan commands follow a consistent pattern and are extensible, allowing you to add custom commands for your application's specific needs.

graph LR A[Artisan] --> B[Controllers] A --> C[Models] A --> D[Migrations] A --> E[Middleware] A --> F[Policies] A --> G[Resources] A --> H[Mail] A --> I[Events] A --> J[Jobs] A --> K[Custom Commands]

Using Artisan is like having a skilled assistant who can quickly create properly formatted files and perform routine tasks, allowing you to focus on the creative aspects of development.

Development Server

Laravel includes a built-in development server, making it easy to start working on your application without configuring a full web server.


# Start the Laravel development server
php artisan serve

# Specify a different host and port
php artisan serve --host=0.0.0.0 --port=8080
            

The development server is like a prototype workshop - it's perfect for development and testing but not intended for production use.

Alternative Local Development Options

Laravel Valet (macOS)

Valet is a lightweight development environment for macOS that makes it easy to work with multiple Laravel projects.


# Install Valet using Composer
composer global require laravel/valet

# Set up Valet
valet install

# Link your current directory to Valet
valet park
            

With Valet, your projects are accessible at http://projectname.test automatically.

Laravel Homestead (Cross-platform)

Homestead is a pre-packaged Vagrant box with all the tools needed for Laravel development.


# Install Homestead
git clone https://github.com/laravel/homestead.git ~/Homestead
cd ~/Homestead
git checkout release
bash init.sh
            

Configure your Homestead.yaml file and run vagrant up to start the environment.

Laravel Sail (Docker)

As mentioned earlier, Sail provides a Docker-based development environment:


# Start Sail
./vendor/bin/sail up

# Run Artisan commands through Sail
./vendor/bin/sail artisan migrate
            

These development environment options are like different types of workshops - from a simple portable workbench (serve) to a complete prefabricated workshop (Homestead/Sail) - choose the one that best fits your workflow.

Application Key

Every Laravel application requires an application key for security purposes. This key is used for encrypting session data, cookies, and other sensitive information.


# Generate a new application key
php artisan key:generate
            

The key is stored in your .env file as APP_KEY. Think of this key as the master lock for your application's security features - without it, sensitive data would be vulnerable.

When you create a new Laravel project, the key is usually generated automatically. However, if you clone an existing project or if the key is missing for any reason, you'll need to generate it manually.

Front-End Setup

Laravel provides a comfortable starting point for front-end development with built-in support for popular tools.

Vite Integration

Laravel 10 uses Vite for asset compilation by default. Your project comes with a configured vite.config.js file.


# Install Node.js dependencies
npm install

# Start the Vite development server
npm run dev

# Build assets for production
npm run build
            

Vite provides hot module replacement (HMR) for a smoother development experience, automatically refreshing your browser when you make changes to your assets.

CSS and JavaScript

Laravel's front-end scaffolding places your CSS and JavaScript files in the resources/css and resources/js directories. These files are compiled and placed in public/build.

This asset pipeline is like having an automated assembly line that takes your raw materials (source files) and processes them into optimized final products (compiled assets) ready for distribution.

Common Setup Issues and Solutions

graph TD A[Common Setup Issues] --> B[Permission Problems] A --> C[Database Connection Errors] A --> D[Missing Dependencies] A --> E[URL Configuration] B --> B1[Fix: chmod -R 755 storage bootstrap/cache] C --> C1[Fix: Check .env configuration] D --> D1[Fix: composer install --no-scripts] E --> E1[Fix: Update APP_URL in .env]

Permission Issues

Laravel needs write access to the storage and bootstrap/cache directories. If you encounter permission errors:


chmod -R 755 storage bootstrap/cache

Database Connection Errors

If your application can't connect to the database, verify your .env settings and ensure your database server is running.

Missing Dependencies

If you're missing required extensions or dependencies:


# Check PHP extensions
php -m

# Install missing composer dependencies
composer install
            

URL Configuration

Ensure your APP_URL in the .env file matches your development server's URL to prevent issues with asset loading and redirects.

Best Practices for Project Setup

Following these practices is like establishing good workshop protocols - they may take a little time upfront but prevent countless problems down the line.

Practice Activity

Create a New Laravel Project

  1. Install Laravel using your preferred method (Composer, Laravel Installer, or Sail)
  2. Configure your database connection in the .env file
  3. Run migrations to set up the initial database tables
  4. Start the development server and ensure you can access the welcome page

Explore the Project Structure

  1. Navigate through the different directories in your Laravel project
  2. Open key files like routes/web.php, app/Http/Controllers/Controller.php, and resources/views/welcome.blade.php
  3. Create a diagram or notes about how these components relate to each other

Create Custom Artisan Command

  1. Use php artisan make:command GreetingCommand to create a custom command
  2. Implement the command to display a greeting message with the current date and time
  3. Register the command in app/Console/Kernel.php
  4. Test your command by running php artisan greeting

Summary

In the next lecture, we'll explore Laravel's routing and controller system, building on this foundation to create functional applications.