A Beginner’s Guide to Setting Up a Project in Laravel

Share this article

A Beginner's Guide to Setting Up a Project in Laravel

In this article, we’ll walk through the building blocks of Laravel and how can we use Laravel to set up a small project.

Laravel is a robust and elegant PHP web application framework that has gained immense popularity among developers for its simplicity, versatility, and powerful features. Over the years, Laravel has become the go-to PHP framework for both big and small projects.

Prerequisites: Getting Started with Laravel

Before diving into Laravel development, we must ensure we have all the necessary tools and software installed. Here’s what we’ll need:

  • PHP. Laravel runs on PHP, so the first step is to ensure you have PHP installed on your system. If you’re not sure whether PHP is installed, open a terminal or command prompt and type php -v. If PHP is installed, you’ll see a version number. If not, you’ll need to install it.

    To install PHP in your machine we have a couple of options:

    Local installation. You can install PHP directly on your computer. Visit the PHP downloads page to get the latest version for your operating system.

    Laravel Homestead. For a more streamlined setup, especially if you’re new to PHP development, consider using Laravel Homestead. Homestead is a pre-packaged Vagrant box that provides a complete development environment for Laravel. You can find installation instructions here.

  • Composer. Laravel uses Composer for dependency management. Composer is the default PHP dependency manager, and is widely used and well documented.
  • Laravel Installer. Laravel can be globally installed on our system using the Laravel Installer, a convenient command-line tool that streamlines and simplifies the process of creating new Laravel projects. To install it globally on your system, follow these steps:
    1. Open a terminal or command prompt.
    2. Run the following Composer command:
    composer global require laravel/installer
    

    Once installation is complete, make sure Composer’s global bin directory is in your system’s “PATH” so you can run the laravel command from anywhere.

    If you prefer a more lightweight alternative to Homestead, you might consider Laravel Herd. Herd is a Docker-based local development environment specifically tailored for Laravel projects. You can learn more about Herd and how to set it up here.

By setting up your development environment with PHP, Composer, and the Laravel Installer (or exploring options like Homestead or Herd), you’ll be well-prepared to embark on your Laravel journey. In the following sections, we’ll go through the process of creating a new Laravel project, exploring its directory structure, and configuring the development environment.

Setting Up a New Laravel Project

Now that we have our development environment ready, it’s time to create a new Laravel project. To create a new, “empty” project, we can use the following terminal command:

composer create-project --prefer-dist laravel/laravel project-name

project-name should be replaced with the actual project name. This command will download the latest version of Laravel and set up a new project directory with all the necessary files and dependencies.

Directory Structure: Navigating A Laravel Project

Upon creating a new Laravel project, we’ll find ourselves in a well-organized directory structure. Understanding this structure is crucial for effective Laravel development. Here are some of the key directories and their purposes:

  • app. This directory houses our application’s core logic, including controllers, models, and service providers.
  • bootstrap. Laravel’s bootstrapping and configuration files reside here.
  • config. Configuration files for various components of our application can be found here, allowing us to find and customize settings like database connections and services from a single point in the project.
  • Database. In this directory, we’ll define our database migrations and seeds to be used by Laravel’s Eloquent ORM. Eloquent simplifies database management.
  • public. Publicly accessible assets like CSS, JavaScript, and images belong here. This directory also contains the entry point for our application, the index.php file.
  • resources. Our application’s raw, uncompiled assets, such as Blade templates, Sass, and JavaScript, are stored here.
  • routes. Laravel’s routing configuration is managed in this directory.
  • storage. Temporary and cache files, as well as logs, are stored here.
  • vendor. Composer manages our project’s dependencies in this directory. All downloaded libraries will be in this directory.

Configuration: Database Setup and Environment Variables

To configure our database connection, we need to open the .env file in the project’s root directory. Here, we can specify the database type, host, username, password, and database name. Thanks to Eloquent ORM, Laravel supports multiple database connections, making it versatile for various project requirements.

Understanding the .env file

The .env file is where we define environment-specific configuration values, such as database connection details, API keys, and other settings. Let’s take a look at a simple example of what you might find in a .env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_database
DB_USERNAME=my_username
DB_PASSWORD=my_password

In this example:

  • DB_CONNECTION specifies the type of database driver we’re using (such as MySQL, PostgreSQL, SQLite).
  • DB_HOST specifies the host where our database server is located.
  • DB_PORT specifies the port on which the database server is running.
  • DB_DATABASE specifies the name of the database we want to connect to.
  • DB_USERNAME and DB_PASSWORD specify the username and password required to access the database.

Using environment variables

It’s crucial to keep sensitive information like database credentials secure. Laravel encourages the use of environment variables to achieve this. Instead of hardcoding our credentials in the .env file, we can reference them in our configuration files.

For example, in our Laravel configuration files (located in the config/ directory), we can reference the database configuration like this:

'mysql' => [
    'driver' => env('DB_CONNECTION', 'mysql'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    // ...
],

Here, the env() function retrieves the value of the specified environment variable from the .env file. If the variable isn’t found, it falls back to a default value provided as the second argument.

By using configuration files, we can store sensitive data in a more secure location and easily switch configurations between environments (like development and production).

With our Laravel project created, directories organized, and database configured, we’re ready to start building our web application. In the following sections, we’ll focus on routing, controllers, and working with Blade templates for our frontend views.

Routing, Controllers, and Views: The Heart of Your Laravel Application

In Laravel, routing, controllers, and views work together to handle HTTP requests and render dynamic web pages. Understanding these concepts is essential for creating web applications with Laravel.

In a nutshell, HTTP requests are received by the router, which then knows which controller should handle the action. The controller is responsible for processing the information and showing the processed information through views.

Routing

In Laravel, we can define routes in the routes/web.php file. A basic route definition looks like this:

Route::get('/welcome', function () {
    return view('welcome');
});

This example sets up a route that, when accessed, returns the welcome view. Routes can also be used to call controller actions, as we mentioned above, allowing us to organize the code more efficiently.

Creating a controller

Controllers serve as the bridge between our routes and the logic of our application. To create a controller, we can use the make:controller command:

php artisan make:controller YourControllerName

Our new controller contains methods that correspond to different actions in our application, such as displaying a page or processing form data.

Views and Blade templates

Views in Laravel are responsible for presenting our application’s data to users. Out of the box, Laravel uses a templating engine called Blade, which simplifies the creation of dynamic, reusable views. Here’s an example of rendering a view in a controller method:

public function index()
{
    $data = ['name' => 'John'];
    return view('welcome', $data);
}

In this example, the welcome view is rendered with data, in this case, 'name' is passed into it.

Blade is a very powerful templating engine that allows for the creation of dynamic content through conditional statements, loops, and so on.

Database Migration and Seeding

Laravel’s database migration and seeding system allows us to define our database schema and populate it with initial data. We can look at migrations as version-controlled database changes, and seeding as the process of adding sample data.

Migrations and seeding are super powerful concepts that allow for database consistency across environments.

To create a migration, we can use the make:migration command:

php artisan make:migration create_table_name

We can then edit the generated migration file to define our table structure, and then use Artisan to run the migration:

php artisan migrate

Seeding is often used to populate tables with initial data for testing and development. To create seeders we can use the make:seeder command and run them with:

php artisan db:seed

Creating Models for Database Interaction

Laravel’s Eloquent ORM simplifies database interactions by allowing us to work with databases as if they were objects. To create a model, we use the make:model command:

php artisan make:model YourModelName

Define the table and relationships in the model to enable easy data retrieval and manipulation. For example, to retrieve all records from a users table:

$users = YourModelName::all();

Armed with all this knowledge, incorporating routing, controllers, views, database migration, seeding, and models, we’re well on our way to building dynamic web applications with Laravel. In the next sections, we’ll delve deeper into creating a simple CRUD application and exploring more advanced Laravel features.

Creating a Simple CRUD Application in Laravel

Let’s take our Laravel journey to the next level by building a CRUD application — in this case, a simple book registration application, where we can create, read, update, and delete books. This hands-on exercise will help us understand how to implement CRUD operations in Laravel.

For the sake of the size of this article, we’ll focus on creating only the initial page of the application, so it’s up to you to finish this application!

Step 1: Create a migration for the books table

To generate a migration for the books table, let’s use the following command:

php artisan make:migration create_books_table

This command generates a migration file for creating the books table in the database. Next, edit the generated migration file we just created (database/migrations/YYYY_MM_DD_create_books_table.php) to define the table structure:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateBooksTable extends Migration
{
    public function up()
    {
        Schema::create('books', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->string('author');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('books');
    }
}

In this migration file, we define the structure of the books table, including its columns (id, title, author, timestamps). Then we want to run the migration to create the table:

php artisan migrate

This command executes the migration file and creates the books table in the database.

Step 2: Create a seeder for the books table

Next, we want to generate a seeder for the books table to populate it with some initial data:

php artisan make:seeder BooksTableSeeder

This command generates a seeder file for populating the books table with initial data.

Edit the seeder file (database/seeders/BooksTableSeeder.php) to define sample book data:

use Illuminate\Database\Seeder;

class BooksTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('books')->insert([
            ['title' => 'Book 1', 'author' => 'Author A'],
            ['title' => 'Book 2', 'author' => 'Author B'],
            ['title' => 'Book 3', 'author' => 'Author C'],
        ]);
    }
}

In this seeder file, we define sample book data that will be inserted into the books table. In this particular case we are creating books from 1 to 3 and authors from A to C.

Run the seeder to populate the books table:

php artisan db:seed --class=BooksTableSeeder

This command executes the seeder file and populates the books table with the defined sample data.

Step 3: Create a controller

Generate a controller for managing books:

php artisan make:controller BookController

This command generates a controller file (BookController.php) that contains methods for handling CRUD operations related to books. With the controller created, let’s focus on implementing CRUD methods in the BookController. It’s located in app/Http/Controllers/BookController.php:

use App\Book; // Import the Book model

public function index()
{
    $books = Book::all();
    return view('books.index', compact('books'));
}

public function create()
{
    return view('books.create');
}

public function store(Request $request)
{
    $book = new Book;
    $book->title = $request->input('title');
    $book->author = $request->input('author');
    $book->save();

    return redirect()->route('books.index');
}

// Implement edit, update, show, and delete methods similarly

In this controller file, we define methods for handling CRUD operations related to books. For example, the index method retrieves all books from the database and passes them to the index view, while the store method creates a new book record based on the data submitted through a form. The create() method is responsible for displaying the form for creating a new book record. When a user navigates to the route associated with this method, Laravel will execute this function and return a view called books.create.

Step 4: Create views

Create views for listing, creating, and editing books in the resources/views folder.

Example View (create.blade.php):

@extends('layout')

@section('content')
  <h1>Create a New Book</h1>
  <form method="POST" action="{{ route('books.store') }}">
    @csrf
    <div class="form-group">
      <label for="title">Title</label>
      <input type="text" name="title" class="form-control" id="title" placeholder="Enter book title">
    </div>
    <div class="form-group">
      <label for="author">Author</label>
      <input type="text" name="author" class="form-control" id="author" placeholder="Enter author name">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>
  <a href="{{ route('books.index') }}">Back to the list</a>
@endsection

In this example, the create view contains a form for adding a new book. The form submits data to the store method of the BookController. The @csrf directive generates a CSRF token to protect against cross-site request forgery.

With this example, you should be able to implement the controller’s methods and views for the rest of the CRUD operations by yourself, so get to work!

Conclusion

In this article, we looked at the basics of a Laravel application: how we can use the command line to help us build an application, the structure of a Laravel application, and how to create a CRUD application in Laravel.

I hope this article was useful and that you’re now capable of using Laravel to create your applications and expand the information here with more advanced topics. More information on Laravel can be found at the official Laravel website.

You can also explore Laravel boilerplates to find a pre-configured setup and learn its best practices.

Claudio RibeiroClaudio Ribeiro
View Author

Cláudio Ribeiro is a software developer, traveler, and writer from Lisbon. He's the author of the book An IDE Called Vim. When he is not developing some cool feature at Kununu he is probably backpacking somewhere in the world or messing with some obscure framework.

laravel
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week
Loading form