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:
- PHP >= 8.1 - Laravel 10 requires PHP 8.1 or higher
- Composer - The PHP dependency manager
- Database - MySQL, PostgreSQL, SQLite, or SQL Server
- Web Server - Apache, Nginx, or Laravel's built-in server
- Extensions - BCMath, Ctype, Fileinfo, JSON, Mbstring, OpenSSL, PDO, Tokenizer, XML
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.
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.
Key Directories Explained
- app/ - Contains the core code of your application. Think of this as your workshop where most of the creation happens.
- config/ - Configuration files. Like the control panel for your application's settings.
- database/ - Database migrations, seeders, and factories. The blueprint for your data structure.
- public/ - Publicly accessible files and the entry point (index.php). The front door and lobby of your application.
- resources/ - Uncompiled assets and views. The raw materials and templates for your application's interface.
- routes/ - Route definitions. The roadmap that defines how users navigate your application.
- storage/ - Application storage for logs, compiled templates, file uploads, etc. The filing cabinet and storage room.
- tests/ - Automated tests. The quality control department ensuring everything works as expected.
- vendor/ - Composer dependencies. The supply warehouse of external components.
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
- app.php - Core application settings like name, environment, timezone, and providers
- database.php - Database connection settings for different environments
- auth.php - Authentication configuration including guards and providers
- cache.php - Cache storage and behavior configuration
- mail.php - Email sending configuration
- services.php - Third-party service credentials (Stripe, Mailgun, etc.)
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:
- Version Control - Database schema changes are tracked in your code repository
- Team Collaboration - All developers work with the same database structure
- Environment Consistency - Development, staging, and production use identical schemas
- Deployment Automation - Database changes can be deployed systematically
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.
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
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
- Version Control from Day One - Initialize a Git repository immediately and commit your initial project structure
- Environment-Specific Configuration - Keep sensitive data and environment-specific settings in
.env(and exclude it from version control) - Use .env.example - Maintain an updated
.env.examplefile to document required environment variables - Consistent Team Environments - Use Docker or Vagrant to ensure all team members have identical environments
- Document Setup Steps - Create a README.md with clear setup instructions for new team members
- Automate Where Possible - Use scripts to automate repetitive setup tasks
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
- Install Laravel using your preferred method (Composer, Laravel Installer, or Sail)
- Configure your database connection in the
.envfile - Run migrations to set up the initial database tables
- Start the development server and ensure you can access the welcome page
Explore the Project Structure
- Navigate through the different directories in your Laravel project
- Open key files like
routes/web.php,app/Http/Controllers/Controller.php, andresources/views/welcome.blade.php - Create a diagram or notes about how these components relate to each other
Create Custom Artisan Command
- Use
php artisan make:command GreetingCommandto create a custom command - Implement the command to display a greeting message with the current date and time
- Register the command in
app/Console/Kernel.php - Test your command by running
php artisan greeting
Summary
- Laravel can be installed via Composer, the Laravel Installer, or Laravel Sail with Docker
- The project structure is organized into logical directories for different aspects of your application
- Configuration happens through files in the
config/directory and environment variables in.env - Database setup involves configuring connection details and running migrations
- Artisan provides a powerful command-line interface for common development tasks
- Multiple options exist for local development environments, from the simple built-in server to Docker-based solutions
In the next lecture, we'll explore Laravel's routing and controller system, building on this foundation to create functional applications.