Установка
- 1. Встречайте Laravel
- 2. Создание приложения Laravel
- Initial Configuration
- Local Installation Using Herd
- Docker Installation Using Sail
- IDE Support
- Next Steps
1. Встречайте Laravel
Laravel - это фреймворк для веб-приложений с выразительным, элегантным синтаксисом. Веб-фреймворк предоставляет структуру и отправную точку для создания вашего приложения, позволяя вам сосредоточиться на создании чего-то удивительного, в то время как мы заботимся о деталях.
Laravel стремится предоставить потрясающий опыт разработки, предлагая мощные возможности, такие как полная реализация внедрения зависимостей, выразительный уровень абстракции для работы с базой данных, очереди и запланированные задачи, модульное и интеграционное тестирование и многое другое.
Независимо от того, новичок ли вы в PHP-фреймворках или имеете многолетний опыт, Laravel — это фреймворк, который может расти вместе с вами. Мы поможем вам сделать первые шаги в веб-разработке или ускорим ваш рост, если вы хотите вывести свои навыки на новый уровень. Мы с нетерпением ждем, что вы создадите.
Новичок в Laravel? Ознакомьтесь с Laravel Bootcamp, чтобы пройти практическое знакомство с фреймворком, пока мы шаг за шагом проведем вас через создание вашего первого приложения на Laravel.
Существует множество инструментов и фреймворков для создания веб-приложений. Однако мы считаем, что Laravel — лучший выбор для разработки современных full-stack веб-приложений.
1.1.1. Прогрессивный фреймворк
Мы называем Laravel "прогрессивным" фреймворком. Это означает, что Laravel растет вместе с вами. Если вы только начинаете свой путь в веб-разработке, обширная библиотека документации, руководств и видеоуроков Laravel поможет вам освоить основы, не перегружая вас.
Если вы опытный разработчик, Laravel предоставляет мощные инструменты для внедрения зависимостей, модульного тестирования, работы с очередями, событиями в реальном времени и многого другого. Laravel идеально подходит для создания профессиональных веб-приложений и готов справляться с корпоративными нагрузками.
1.1.2. Масштабируемый фреймворк
Laravel невероятно масштабируем. Благодаря масштабируемости PHP и встроенной поддержке Laravel для быстрых распределённых систем кэширования, таких как Redis, горизонтальное масштабирование с Laravel становится простым. Фактически, приложения Laravel легко масштабировались для обработки сотен миллионов запросов в месяц.
Нужна экстремальная масштабируемость? Платформы, такие как Laravel Vapor, позволяют запускать ваше Laravel-приложение с практически неограниченным масштабом на новейшей серверлесс-технологии AWS.
1.1.3. Фреймворк сообщества
Laravel объединяет лучшие пакеты в экосистеме PHP, чтобы предложить самый надёжный и удобный для разработчиков фреймворк. Кроме того, тысячи талантливых разработчиков со всего мира внесли свой вклад в разработку фреймворка. Кто знает, возможно, вы тоже станете участником сообщества Laravel.
2. Создание приложения Laravel
2.1. Установка PHP и установщика Laravel
Перед созданием вашего первого Laravel-приложения убедитесь, что на вашем локальном компьютере установлены PHP, Composer и установщик Laravel. Кроме того, вы должны установить либо Node и NPM, либо Bun, чтобы иметь возможность компилировать фронтенд-ассеты вашего приложения.
Если PHP и Composer не установлены на вашем локальном компьютере, выполните следующие команды для установки PHP, Composer и установщика Laravel на macOS, Windows или Linux:
/bin/bash -c "$(curl -fsSL https://php.new/install/mac/8.4)"
# Run as administrator...Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://php.new/install/windows/8.4'))
/bin/bash -c "$(curl -fsSL https://php.new/install/linux/8.4)"
После выполнения одной из приведённых выше команд вам следует перезапустить сессию терминала. Чтобы обновить PHP, Composer и установщик Laravel после их установки через php.new
, вы можете снова выполнить эту команду в терминале.
Если PHP и Composer уже установлены, вы можете установить установщик Laravel с помощью Composer:
composer global require laravel/installer
Для полноценного графического интерфейса установки и управления PHP ознакомьтесь с Laravel Herd.
2.2. Создание приложения
После установки PHP, Composer и установщика Laravel вы готовы создать новое Laravel-приложение. Установщик Laravel предложит вам выбрать предпочитаемую тестовую среду, базу данных и стартовый комплект:
laravel new example-app
После создания приложения вы можете запустить локальный сервер разработки Laravel, обработчик очередей и сервер разработки Vite, используя скрипт dev
из Composer:
cd example-app php artisan serve
После запуска сервера разработки ваше приложение будет доступно в веб-браузере по адресу http://localhost:8000. Далее вы можете сделать следующие шаги в экосистеме Laravel. Конечно, вы также можете настроить базу данных.
Если вы хотите начать разработку Laravel-приложения с готового решения, рассмотрите возможность использования одного из наших стартовых комплектов. Стартовые комплекты Laravel предоставляют базовую структуру для аутентификации на стороне бэкенда и фронтенда вашего нового Laravel-приложения.
Initial Configuration
All of the configuration files for the Laravel framework are stored in the config
directory.
Each option is documented, so feel free to look through the files and get familiar with the options
available to you.
Laravel needs almost no additional configuration out of the box. You are free to get started developing!
However, you may wish to review the config/app.php
file and its documentation. It contains
several options such as timezone
and locale
that you may wish to change
according to your application.
Environment Based Configuration
Since many of Laravel's configuration option values may vary depending on whether your application is
running on your local machine or on a production web server, many important configuration values are
defined using the .env
file that exists at the root of your application.
Your .env
file should not be committed to your application's source control, since each
developer / server using your application could require a different environment configuration.
Furthermore, this would be a security risk in the event an intruder gains access to your source control
repository, since any sensitive credentials would be exposed.
For more information about the .env
file and environment based configuration, check out the
full configuration documentation.
Databases and Migrations
Now that you have created your Laravel application, you probably want to store some data in a database.
By default, your application's .env
configuration file specifies that Laravel will be
interacting with a SQLite database.
During the creation of the application, Laravel created a database/database.sqlite
file for
you, and ran the necessary migrations to create the application's database tables.
If you prefer to use another database driver such as MySQL or PostgreSQL, you can update your
.env
configuration file to use the appropriate database. For example, if you wish to use
MySQL, update your .env
configuration file's DB_*
variables like so:
DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=laravelDB_USERNAME=rootDB_PASSWORD=
If you choose to use a database other than SQLite, you will need to create the database and run your application's database migrations:
php artisan migrate
If you are developing on macOS or Windows and need to install MySQL, PostgreSQL, or Redis locally, consider using Herd Pro.
Directory Configuration
Laravel should always be served out of the root of the "web directory" configured for your web server. You should not attempt to serve a Laravel application out of a subdirectory of the "web directory". Attempting to do so could expose sensitive files present within your application.
Local Installation Using Herd
Laravel Herd is a blazing fast, native Laravel and PHP development environment for macOS and Windows. Herd includes everything you need to get started with Laravel development, including PHP and Nginx.
Once you install Herd, you're ready to start developing with Laravel. Herd includes command line tools
for php
, composer
, laravel
, expose
, node
,
npm
, and nvm
.
Herd Pro augments Herd with additional powerful features, such as the ability to create and manage local MySQL, Postgres, and Redis databases, as well as local mail viewing and log monitoring.
Herd on macOS
If you develop on macOS, you can download the Herd installer from the Herd website. The installer automatically downloads the latest version of PHP and configures your Mac to always run Nginx in the background.
Herd for macOS uses dnsmasq to support "parked"
directories. Any Laravel application in a parked directory will automatically be served by Herd. By
default, Herd creates a parked directory at ~/Herd
and you can access any Laravel application
in this directory on the .test
domain using its directory name.
After installing Herd, the fastest way to create a new Laravel application is using the Laravel CLI, which is bundled with Herd:
cd ~/Herdlaravel new my-appcd my-appherd open
Of course, you can always manage your parked directories and other PHP settings via Herd's UI, which can be opened from the Herd menu in your system tray.
You can learn more about Herd by checking out the Herd documentation.
Herd on Windows
You can download the Windows installer for Herd on the Herd website. After the installation finishes, you can start Herd to complete the onboarding process and access the Herd UI for the first time.
The Herd UI is accessible by left-clicking on Herd's system tray icon. A right-click opens the quick menu with access to all tools that you need on a daily basis.
During installation, Herd creates a "parked" directory in your home directory at
%USERPROFILE%\Herd
. Any Laravel application in a parked directory will automatically be
served by Herd, and you can access any Laravel application in this directory on the .test
domain using its directory name.
After installing Herd, the fastest way to create a new Laravel application is using the Laravel CLI, which is bundled with Herd. To get started, open Powershell and run the following commands:
cd ~\Herdlaravel new my-appcd my-appherd open
You can learn more about Herd by checking out the Herd documentation for Windows.
Docker Installation Using Sail
We want it to be as easy as possible to get started with Laravel regardless of your preferred operating system. So, there are a variety of options for developing and running a Laravel application on your local machine. While you may wish to explore these options at a later time, Laravel provides Sail, a built-in solution for running your Laravel application using Docker.
Docker is a tool for running applications and services in small, light-weight "containers" which do not interfere with your local machine's installed software or configuration. This means you don't have to worry about configuring or setting up complicated development tools such as web servers and databases on your local machine. To get started, you only need to install Docker Desktop.
Laravel Sail is a light-weight command-line interface for interacting with Laravel's default Docker configuration. Sail provides a great starting point for building a Laravel application using PHP, MySQL, and Redis without requiring prior Docker experience.
Already a Docker expert? Don't worry! Everything about Sail can be customized using the
docker-compose.yml
file included with Laravel.
Sail on macOS
If you're developing on a Mac and Docker Desktop is already installed, you can use a simple terminal command to create a new Laravel application. For example, to create a new Laravel application in a directory named "example-app", you may run the following command in your terminal:
curl -s "https://laravel.build/example-app" | bash
Of course, you can change "example-app" in this URL to anything you like - just make sure the application name only contains alpha-numeric characters, dashes, and underscores. The Laravel application's directory will be created within the directory you execute the command from.
Sail installation may take several minutes while Sail's application containers are built on your local machine.
After the application has been created, you can navigate to the application directory and start Laravel Sail. Laravel Sail provides a simple command-line interface for interacting with Laravel's default Docker configuration:
cd example-app ./vendor/bin/sail up
Once the application's Docker containers have started, you should run your application's database migrations:
./vendor/bin/sail artisan migrate
Finally, you can access the application in your web browser at: http://localhost.
To continue learning more about Laravel Sail, review its complete documentation.
Sail on Windows
Before we create a new Laravel application on your Windows machine, make sure to install Docker Desktop. Next, you should ensure that Windows Subsystem for Linux 2 (WSL2) is installed and enabled. WSL allows you to run Linux binary executables natively on Windows 10. Information on how to install and enable WSL2 can be found within Microsoft's developer environment documentation.
After installing and enabling WSL2, you should ensure that Docker Desktop is configured to use the WSL2 backend.
Next, you are ready to create your first Laravel application. Launch Windows Terminal and begin a new terminal session for your WSL2 Linux operating system. Next, you can use a simple terminal command to create a new Laravel application. For example, to create a new Laravel application in a directory named "example-app", you may run the following command in your terminal:
curl -s https://laravel.build/example-app | bash
Of course, you can change "example-app" in this URL to anything you like - just make sure the application name only contains alpha-numeric characters, dashes, and underscores. The Laravel application's directory will be created within the directory you execute the command from.
Sail installation may take several minutes while Sail's application containers are built on your local machine.
After the application has been created, you can navigate to the application directory and start Laravel Sail. Laravel Sail provides a simple command-line interface for interacting with Laravel's default Docker configuration:
cd example-app ./vendor/bin/sail up
Once the application's Docker containers have started, you should run your application's database migrations:
./vendor/bin/sail artisan migrate
Finally, you can access the application in your web browser at: http://localhost.
To continue learning more about Laravel Sail, review its complete documentation.
Developing Within WSL2
Of course, you will need to be able to modify the Laravel application files that were created within your WSL2 installation. To accomplish this, we recommend using Microsoft's Visual Studio Code editor and their first-party extension for Remote Development.
Once these tools are installed, you may open any Laravel application by executing the code .
command from your application's root directory using Windows Terminal.
Sail on Linux
If you're developing on Linux and Docker Compose is already installed, you can use a simple terminal command to create a new Laravel application.
First, if you are using Docker Desktop for Linux, you should execute the following command. If you are not using Docker Desktop for Linux, you may skip this step:
docker context use default
Then, to create a new Laravel application in a directory named "example-app", you may run the following command in your terminal:
curl -s https://laravel.build/example-app | bash
Of course, you can change "example-app" in this URL to anything you like - just make sure the application name only contains alpha-numeric characters, dashes, and underscores. The Laravel application's directory will be created within the directory you execute the command from.
Sail installation may take several minutes while Sail's application containers are built on your local machine.
After the application has been created, you can navigate to the application directory and start Laravel Sail. Laravel Sail provides a simple command-line interface for interacting with Laravel's default Docker configuration:
cd example-app ./vendor/bin/sail up
Once the application's Docker containers have started, you should run your application's database migrations:
./vendor/bin/sail artisan migrate
Finally, you can access the application in your web browser at: http://localhost.
To continue learning more about Laravel Sail, review its complete documentation.
Choosing Your Sail Services
When creating a new Laravel application via Sail, you may use the with
query string variable
to choose which services should be configured in your new application's docker-compose.yml
file. Available services include mysql
, pgsql
, mariadb
,
redis
, memcached
, meilisearch
, typesense
,
minio
, selenium
, and mailpit
:
curl -s "https://laravel.build/example-app?with=mysql,redis" | bash
If you do not specify which services you would like configured, a default stack of mysql
,
redis
, meilisearch
, mailpit
, and selenium
will be
configured.
You may instruct Sail to install a default Devcontainer by
adding the devcontainer
parameter to the URL:
curl -s "https://laravel.build/example-app?with=mysql,redis&devcontainer" | bash
IDE Support
You are free to use any code editor you wish when developing Laravel applications; however, PhpStorm offers extensive support for Laravel and its ecosystem, including Laravel Pint.
In addition, the community maintained Laravel Idea PhpStorm plugin offers a variety of helpful IDE augmentations, including code generation, Eloquent syntax completion, validation rule completion, and more.
Next Steps
Now that you have created your Laravel application, you may be wondering what to learn next. First, we strongly recommend becoming familiar with how Laravel works by reading the following documentation:
How you want to use Laravel will also dictate the next steps on your journey. There are a variety of ways to use Laravel, and we'll explore two primary use cases for the framework below.
New to Laravel? Check out the Laravel Bootcamp for a hands-on tour of the framework while we walk you through building your first Laravel application.
Laravel the Full Stack Framework
Laravel may serve as a full stack framework. By "full stack" framework we mean that you are going to use Laravel to route requests to your application and render your frontend via Blade templates or a single-page application hybrid technology like Inertia. This is the most common way to use the Laravel framework, and, in our opinion, the most productive way to use Laravel.
If this is how you plan to use Laravel, you may want to check out our documentation on frontend development, routing, views, or the Eloquent ORM. In addition, you might be interested in learning about community packages like Livewire and Inertia. These packages allow you to use Laravel as a full-stack framework while enjoying many of the UI benefits provided by single-page JavaScript applications.
If you are using Laravel as a full stack framework, we also strongly encourage you to learn how to compile your application's CSS and JavaScript using Vite.
If you want to get a head start building your application, check out one of our official application starter kits.
Laravel the API Backend
Laravel may also serve as an API backend to a JavaScript single-page application or mobile application. For example, you might use Laravel as an API backend for your Next.js application. In this context, you may use Laravel to provide authentication and data storage / retrieval for your application, while also taking advantage of Laravel's powerful services such as queues, emails, notifications, and more.
If this is how you plan to use Laravel, you may want to check out our documentation on routing, Laravel Sanctum, and the Eloquent ORM.
Need a head start scaffolding your Laravel backend and Next.js frontend? Laravel Breeze offers an API stack as well as a Next.js frontend implementation so you can get started in minutes.