How to use Laravel framework in PHP
Laravel is a robust PHP framework known for its elegant syntax and comprehensive features. It simplifies the development process and promotes best practices, making it a popular choice among PHP developers.
In this Answer, we'll explore the basics of using the Laravel framework and demonstrate how to set up a simple application.
Note: Before starting, make sure that PHP is installed on the system.
Install Composer
Laravel utilizes Composer, a dependency management tool for PHP. Visit the official Composer website and follow the instructions to install it.
Install Laravel
Once Composer is installed, open the terminal or command prompt and run the following command to install Laravel:
composer global require laravel/installer
This command installs the Laravel installer globally, allowing to create new Laravel projects from anywhere on the machine.
Note: If we do not specify any version during installation, the composer will install the latest stable version of Laravel available at the time.
To install a specific version of Laravel using Composer, we can use the following command.
composer global require "laravel/installer:{version}"
Replace {version} with the specific version number to install. For example, if we want to install the Laravel installer version 4.0.0, we would use the following command.
composer global require "laravel/installer:4.0.0"
Note: If we want to run Laravel commands globally without specifying the full path, we can add the Composer's global bin directory to our system's PATH. This will allow us to run Laravel commands from anywhere on your system. Otherwise, we can encounter the error: laravel: command not found.
Add the Composer global bin directory to PATH
First, check the global Composer bin directory by running the following command.
composer global config bin-dir --absolute
This command will display the absolute path to the global Composer bin directory. Once we have the path, we must add it to our system's PATH environment variable.
For Linux/macOS
Now, we have to add the following line at the end of the
~/.bashrc(for Linux) or~/.bash_profile(for macOS). Replace/path/to/composer/global/binwith the absolute path obtained from the previous command.
export PATH="$PATH:/path/to/composer/global/bin"
Open the terminal and run the following command to append the path in the file.
echo "export PATH="$PATH:/path/to/composer/global/bin"" >> ~/.bashrc
After making changes to the
~/.bashrcfile, we need to reload it to apply the changes. Run the following command to do so.
source ~/.bashrc
For Windows
Open the System Properties dialog.
Click on "Advanced system settings" on the left.
In the "System Properties" window, click the "Environment Variables" button.
Under the "System variables" section, find the "Path" variable and click "Edit."
Add a new entry with the absolute path to the Composer bin directory (e.g.,
C:\Users\YourUserName\AppData\Roaming\Composer\vendor\bin).Click "OK" to save the changes.
Create a new Laravel project
Once the installation is complete, we must navigate to the directory where we want to create our Laravel project. Run the following command to generate a new Laravel project.
laravel new project-name
Replace project-name with the desired name for the project. This command will download the Laravel framework and set up a new project in the specified directory.
Run the installation commands
Here's an interactive terminal to run the installation commands and get hands-on practice.
Laravel project structure
Laravel follows a well-defined project structure, which helps organize the code and separates different aspects of the application. Let's explore the important directories and files within a Laravel project:
app: This directory contains the application's core code, including controllers, models, and other business logic.bootstrap: It holds the files responsible for bootstrapping and initializing the Laravel framework.config: This directory contains various configuration files for the application, such as database settings, caching, and services.database: Here, we'll find database-related files, including migrations, seeds, and the database connection configuration.public: Thepublicdirectory serves as the document root for the application and contains the entry pointindex.php. Publicly accessible files like assets, CSS, and JavaScript should be placed here.resources: This directory contains the application's views, language files, and raw assets like Sass or JavaScript source files.routes: Here, we define the routes for the application. Theweb.phpfile handles web routes, whileapi.phphandles API routes.storage: Laravel uses this directory to store various files, such as logs, cache, and session data.tests: Thetestsdirectory contains automated tests for the application.vendor: Laravel dependencies and packages are installed in this directory.
Configuring the environment
After creating the project, navigate to the project directory using cd project-name. Next, open the .env file in the project root directory. Here, we can configure our application's environment variables, such as the database connection details. Update the necessary variables based on the development environment.
Routing in laravel
Laravel provides a powerful routing system to define URLs that the application responds to. Open the routes/web.php file, and we'll find an example route:
Route::get('/', function () {return view('welcome');});
In this example, the root URL / is mapped to a closure function that returns the welcome view. We can define various routes based on the application's needs, including routes with dynamic parameters, named routes, and route groups.
Creating views
Views in Laravel are responsible for rendering the user interface. Laravel's default view directory is resources/views. There is a file welcome.blade.php in the resources/views directory. By default, it contains the code for the Laravel webpage. We can modify its content to create the view we want.
Here's an example view.
<!DOCTYPE html><html><head><title>Welcome</title></head><body><h1>Welcome to Educative!</h1></body></html>
Run the application
To run the Laravel application, use the following command.
php artisan serve
This command starts the built-in development server provided by Laravel.
Executable application
Following is an executable application containing the Laravel project.
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:b7+51jaHTkygv1leS/H9RI9zhkUD5DJXrNF7QnTnt9Y=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=project_name
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DRIVER=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailhog
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_APP_CLUSTER=mt1
MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"
Conclusion
In this Answer, we covered the basics of using the Laravel framework in PHP. We discussed the installation process and the basic project structure. By leveraging Laravel's features and following its conventions, we can develop scalable and maintainable PHP applications.
Free Resources