What is Laravel Sail and How to Install it?

Are you struggling with complex local development setups for your Laravel projects? Laravel Sail might just be the solution you’ve been waiting for. This powerful Docker-based tool simplifies your development workflow by offering a pre-configured environment with everything you need—PHP, MySQL, Redis, and more—contained within isolated Docker containers. No more manual setup hassles.

In this guide, we’ll walk you through mastering Laravel Sail, whether you’re a seasoned developer or just starting out. From basic setup to advanced features, we’ll cover everything you need to know to make the most of this efficient development environment.

What sets this guide apart? It’s backed by insights from Laravel development experts, offering you a tried-and-true roadmap to streamline your workflow and ensure smooth deployments.

What is Laravel Sail?

Laravel Sail is a lightweight development environment for Laravel applications, using Docker containers to create an isolated workspace. It eliminates the need for manual setup of components like PHP, MySQL, and Redis.

Key features include:

  • Docker Containers: Self-contained units that include all components needed to run your application, ensuring isolated environments for each project.
  • docker-compose.yml: A configuration file that defines services, ports, and settings required for your Laravel app.
  • Sail CLI: A command-line interface for managing containers—starting, stopping, rebuilding, and more.
  • Data Persistence: Volumes maintain data across container restarts, ensuring code, configurations, and databases are preserved.

Laravel Sail offers a simple, consistent, and isolated setup, allowing you to focus on building scalable applications.

Overall, Laravel Sail offers a powerful and efficient solution for streamlining the development workflow. By leveraging Docker containers, this tool ensures consistency, simplifies setup and provides isolation. Hence, it empowers you to focus on building scalable Laravel applications.

What are the Prerequisites to Install Laravel Sail?

Desktop enables you to run applications within isolated containers. Download and install Docker Desktop from the official website for your respective operating system (Windows, macOS, or Linux).

Additional Points to Consider:

  • Windows Users: For Windows users, ensure WSL 2 (Windows Subsystem for Linux 2) is configured as the default backend for Docker Desktop. This allows you to run Linux containers within the Windows environment.
  • Basic Knowledge: Indeed, Sail aims to simplify development. Still,  having a fundamental understanding of PHP, Laravel, and the command line will improve the experience and troubleshooting capabilities.
  • Composer: Composer is a dependency management tool for PHP. It is important for managing dependencies within your Laravel project. Ensure Composer is installed and accessible on your system.

With the prerequisites in place, you’re ready to undertake the Laravel Sail development. But, you must ensure these requirements are in their place. These are the foundations for a smooth and efficient development experience.

How to Install Laravel Sail?

Streamlining your Laravel development workflow starts with a robust development environment. Laravel Sail comes to the rescue, leveraging Docker to create a pre-configured and isolated environment. Here’s how to install and get started with Sail.

Prefer Videos Over Text? Here’s a Quick Setup:

A complete video to install Laravel Sail

Here’s a more detailed process step-by-step:

Step 1: Create a New Laravel Project

Before diving into Sail, you need a Laravel project to work with.

1. Create a New Laravel Project. Use the Laravel Artisan CLI tool to create a new project:

laravel new my-project

Replace my-project with your preferred project name. This command will generate a new Laravel application directory named after your chosen name. Steer into this directory before proceeding: 

cd my-project

Once your project is created, you’re ready to proceed with installing Sail and configuring your development environment.

Step 2: Install Laravel Sail

Streamlining your Laravel development workflow starts with a robust development environment. Laravel Sail comes to the rescue, leveraging Docker to create a pre-configured and isolated environment. Here’s how to install and get started with Sail:

1. Install Laravel Sail: As you already have a Laravel project set up, let’s install Sail. Go to your project directory and execute the following command:

./vendor/bin/sail install

This command performs several important actions:

  • Downloads and configures the necessary Docker images for your development environment.
  • Creates the docker-compose.yml file, which defines the services and configurations for your development containers.
  • Incorporate Sail within your project, preparing it for use.

This command uses the sail binary located within your project’s vendor directory. It interacts with the Docker Compose tool to download pre-built Docker images for your chosen services. Then it configures them based on the specifications defined in the docker-compose.yml file.

Step 3: Choose Database

With Sail installed, it’s time to select the database engine you’ll utilize for your Laravel project. Sail offers support for various database options, ensuring flexibility in your development environment.

  • During Installation: During the Sail installation process (./vendor/bin/sail install), you’ll be prompted to choose your preferred database driver.
  • Available Options: Sail typically provides options for popular database engines like MySQL and Postgres.
  • Selecting the Driver: Select the database driver that best aligns with your project requirements and personal preferences.

Select the desired database driver based on your project’s requirements and familiarity. Sail will automatically configure the chosen database within its corresponding Docker container. You can refer to Docker Hub documents for MySQL and Postgres to configure the database effectively.

You can also modify the database configuration later by editing the DATABASE_URL environment variable in your .env file.

Step 4: Start the Docker Containers

With the database selected, it’s time to bring your development environment to life by starting the Docker containers. Sail provides a convenient command for this purpose.

1. Command Execution: Run the following command in your project directory:

./vendor/bin/sail up -d
  • Explanation:
    • ./vendor/bin/sail up. This command invokes the sail up subcommand, which instructs Sail to start the defined services in the docker-compose.yml file.
    • -d. The -d flag directs Sail to run the containers in detached mode. It means they’ll operate in the background without requiring you to keep the terminal window open.

With this command, Sail initiates the creation and startup of individual Docker containers for each service. It includes PHP, MySQL (or your chosen database), and other essential components. This establishes your fully functional development environment, ready for you to begin working on your Laravel project.

Step 5: Access Application

Once the Docker containers are up and running, you’re just a few steps away from accessing your Laravel application.

1. Open Web Browser: Launch your preferred web browser.

2. Navigate to Application URL: Enter the following address into the address bar: http://localhost:8000

3. Observe the Welcome Screen: If everything is configured correctly, you should be greeted by the Laravel welcome screen, indicating a successful setup.

Now, you’ve successfully installed and configured Laravel Sail. Also, the development environment is all set. Use this streamlined environment to build and test your Laravel applications.

Remember, if you encounter any difficulties during the setup process or require further assistance in Laravel Sail, consider seeking the expertise of a Laravel development agency. Their knowledge and guidance can prove invaluable in navigating complex projects and ensuring a smooth development experience.

Take your web app to the next level with our Laravel development services!

Example: How to Create an Application with Laravel Sail?

To demonstrate how Laravel Sail can be used in real-world development, let’s build a simple To-Do application.

This To-Do app will allow users to add, view, and manage tasks. It will feature basic CRUD (Create, Read, Update, Delete) operations, making it an excellent example to understand how Sail sets up a seamless development environment. By the end of this tutorial, you’ll have a fully functional Laravel app running in a Docker container, showcasing how you can use Laravel Sail to streamline your workflow.

Step 1: Create the Laravel Project

Navigate to your working directory and create a new Laravel project:

laravel new todo-app

Once the project is created, move into the project directory:

cd todo-app

Step 2: Install Laravel Sail

Add Sail to your Laravel project:

composer require laravel/sail --dev

Next, publish the Sail configuration file and install the Docker environment:

php artisan sail:install

When prompted, select MySQL as the database for this example.

Step 3: Start the Docker Containers

With Sail installed, start your Docker containers:

./vendor/bin/sail up -d

This command will set up the PHP, MySQL, and other services needed for Laravel development. The containers will run in the background.

Step 4: Create a To-Do Model and Migration

Let’s create a model and migration for the To-Do feature using artisan commands:

./vendor/bin/sail artisan make:model ToDo -m

This will create a ToDo model and a corresponding migration file in the database/migrations directory.

Step 5: Define the Database Table

Open the newly created migration file (located in the database/migrations directory) and add the following code to define the table structure:

public function up()
{
    Schema::create('to_dos', function (Blueprint $table) {
        $table->id();
        $table->string('task');
        $table->boolean('completed')->default(false);
        $table->timestamps();
    });
}

This creates a table with columns for task name and completion status.

Step 6: Run Migrations

Execute the migration to create the table in the database using sail artisan migrate:

./vendor/bin/sail artisan migrate

Sail will run the migration and create the To-Do table in the MySQL database container.

Step 7: Create the To-Do Controller

Generate a controller to handle To-Do operations:

./vendor/bin/sail artisan make:controller ToDoController

Open the ToDoController.php file and add some basic CRUD operations:

use App\Models\ToDo;
use Illuminate\Http\Request;

class ToDoController extends Controller
{
    public function index()
    {
        $tasks = ToDo::all();
        return view('todos.index', compact('tasks'));
    }

    public function store(Request $request)
    {
        ToDo::create($request->all());
        return redirect()->back();
    }
}

Step 8: Set Up Routes

In the routes/web.php file, add the following routes:

use App\Http\Controllers\ToDoController;

Route::get('/todos', [ToDoController::class, 'index']);
Route::post('/todos', [ToDoController::class, 'store']);

These routes will handle displaying and creating to-do tasks.

Step 9: Create the Front-End View

Create a simple Blade template in resources/views/todos/index.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To-Do App</title>
</head>
<body>
    <h1>To-Do List</h1>
    <form action="/todos" method="POST">
        @csrf
        <input type="text" name="task" placeholder="Enter task">
        <button type="submit">Add</button>
    </form>
    <ul>
        @foreach ($tasks as $task)
            <li>{{ $task->task }} - {{ $task->completed ? 'Completed' : 'Incomplete' }}</li>
        @endforeach
    </ul>
</body>
</html>

Step 10: Test the Application

Now, you can access your To-Do app at http://localhost:8000/todos. You should see a simple form to add tasks and a list of existing tasks.

What are the Use Cases of Laravel Sail?

Laravel Sail transcends its core functionality of simplifying local development setups. It empowers developers with a multitude of use cases, enhancing the overall development workflow and experience. Let’s delve into the key use cases of Laravel Sail:

1. Development Environment

  • Reduced Complexity: Sail prevents the need for manual configuration of individual components. It enables you to focus on writing code and building features, saving time and effort.
  • Consistent Environment: Pre-configured Docker containers ensure a consistent development environment across different machines. It reduces compatibility issues and ensures consistent behavior throughout the development cycle.

2. Collaboration

  • Shared Environment: Team members benefit from a uniform development environment regardless of their local setup. This facilitates collaboration and efficient communication during the development process.
  • Version Control Compatibility: Sail integrates with version control systems, allowing you to share and collaborate on code changes within a consistent environment.

3. Isolation

  • Independent Containers: Each service (PHP, MySQL, etc.) operates within its own container. It benefits in preventing conflicts and dependency issues between projects. Also, these solo containers foster a clean and controlled development environment, minimizing unexpected issues.
  • Simplified Testing: Testing becomes a breeze, as developers can easily spin up fresh containers for each test run. This ensures clean and isolated testing conditions, leading to more reliable results.

4. Testing

  • Isolated Testing Environments: Sail facilitates the development of isolated testing environments. It also enables developers to run tests without affecting the actual application or other project components.
  • Simplified Test Setup: The ability to spin up and tear down containers quickly streamlines the test setup process. It allows developers to focus on writing and executing tests efficiently.

5. Integration

  • Integration Testing: Sail provides a foundation for integration testing, as developers can integrate external services or APIs within their Docker containers. This simulates real-world scenarios and facilitates testing.
  • Simplified Deployment: The use of Docker containers throughout development offers a smooth transition to deployment environments. This containerized structure often aligns with production setups, minimizing potential deployment issues.

Leveraging the diverse use cases of Laravel Sail, you can unlock greater efficiency, collaboration, and consistency throughout the development lifecycle of the Laravel projects.

FAQs About Laravel Sail

Does Laravel Sail use Apache?
No, Laravel Sail does not use Apache as the web server. Instead, it leverages a pre-configured Nginx container within the Docker environment. Nginx is a popular, high-performance web server known for its efficiency and scalability, making it a suitable choice for Laravel applications.
How to add Laravel sail to existing project?
To add Laravel Sail to an existing Laravel project, follow these simple steps: 1. Install the required dependencies. 2. Set up your SSH keys. 3. Install your composer dependencies. 4. Configure the environment file.
Can you use Laravel sail in production?
Laravel Sail is designed specifically for local development. While it's a great tool, it's not recommended for production use. In production, you’ll need to focus more on security, performance, and maintaining stable updates for your environment.

Conclusion

Laravel Sail presents a robust solution for managing Laravel applications with Docker, offering streamlined setup and deployment processes. Its user friendly interface and extensive documentation make it accessible to developers of all levels. With benefits like scalability and ease of use, Laravel Sail is an invaluable tool for improving the Laravel project’s development experience.

Still confused about how Laravel Sail can benefit your application? Our team of Laravel experts is here to provide tailored consultation, solutions, and step-by-step deployment

Want to improve the performance of your Laravel web app?

author
Mayur Upadhyay is a tech professional with expertise in Shopify, WordPress, Drupal, Frameworks, jQuery, and more. With a proven track record in web development and eCommerce development.

Leave a comment