


How to use Laravel to implement separate deployment of front-end and back-end
Apr 23, 2023 am 09:17 AMIn today's Internet world, software services with Web applications as the core are becoming more and more popular. Among them, the Laravel framework, as an excellent development framework for PHP language, not only has efficient performance, but also has a series of advantages such as friendly development experience, rich open source community, powerful ORM and migration system. In Laravel's back-end development, the development model of front-end and back-end separation has gradually become popular recently. This article will introduce how to use Laravel to achieve separate deployment of front-end and back-end.
1. What is front-end and back-end separation
Front-end and front-end separation is a new way of developing web applications, which completely separates the front-end and back-end from a technical perspective. The front-end program is responsible for generating the interface and communicating with the server to obtain data, while the background program is responsible for processing business logic and accessing the database.
This approach has many benefits. First, it can improve the efficiency of front-end and back-end development. Front-end and back-end developers can develop in parallel, reducing dependence on each other; secondly, it can improve application performance. Since front-end and back-end services can be deployed and expanded separately, the overall performance of the system can be greatly improved. In addition, this approach allows both front-end and back-end developers to focus on their respective areas as much as possible, improving code quality and maintainability.
2. Implementation of front-end and back-end separation in Laravel
In Laravel development, the implementation of front-end and back-end separation requires the use of some front-end frameworks. Among them, we can use mainstream frameworks such as Vue.js, React or Angular as front-end development solutions. In Laravel, we can use the following two methods to achieve the separation of front-end and back-end.
- Create a new front-end project
We can create an independent front-end project first, and then interact with the Laravel backend through the API. In this mode, Laravel is only responsible for writing the back-end data API interface, and the front-end uses AJAX or Fetch API to request the back-end data interface. The front-end and back-end codes can be deployed on different servers or ports.
The advantage of this approach is that the separation between the front-end and the back-end is very high. Developers can give full play to their respective advantages while also improving the performance of the application. You can also use some modern front-end frameworks and tools to improve development efficiency and development experience.
The following is a simple example to demonstrate the implementation of this method. Let's take Laravel as the backend and Vue.js as the frontend as an example:
1.1 Create a new Laravel project
First, we need to create a new Laravel project in the command line:
composer?create-project?--prefer-dist?laravel/laravel?blog
1.2 Create a new Vue.js project
Next, we need to create a new Vue.js project:
npm?install?-g?vue-cli vue?init?webpack?frontend
1.3 Configure Laravel and Vue.js
Next, we need to configure the routes/api.php
file to respond to requests from the Vue.js front-end.
Route::get('/todos',?function?()?{ ????return?App\Todo::all(); });
In frontend/src/App.vue
we can use Axios or any other AJAX library to get the backend API. In this example we will use the Axios library.
<template> ??<div class="todo-list"> ????<div class="todo" v-for="todo in todos" :key="todo.id"> ??????<input type="checkbox" :checked="todo.completed" @change="toggle(todo)"> ??????<label>{{?todo.title?}}</label> ????</div> ??</div> </template> <script> import?axios?from?'axios' export?default?{ ??data?()?{ ????return?{ ??????todos:?[] ????} ??}, ??created?()?{ ????axios.get('/api/todos') ??????.then(response?=>?{ ????????this.todos?=?response.data ??????}) ??????.catch(error?=>?{ ????????console.log(error) ??????}) ??}, ??methods:?{ ????toggle?(todo)?{ ??????todo.completed?=?!todo.completed ??????axios.put('/api/todos/'?+?todo.id,?todo) ????????.then(response?=>?{}) ????????.catch(error?=>?{ ??????????console.log(error) ????????}) ????} ??} } </script>
In frontend/config/index.js
we can set the Vue.js frontend to use a different port than the Laravel backend. We can then run and access the application.
php?artisan?serve?--port=8000 cd?frontend npm?start
- Use Laravel Mix to package front-end projects
Another way is to package the front-end code and Laravel back-end code into the same project for deployment. In this mode, Laravel Mix is ??used as a tool for building front-end applications. Laravel Mix is ??a simplified Webpack build tool that allows us to easily package front-end resources.
The advantage of this method is that the front-end and back-end codes will be packaged into a whole, which is convenient for deployment and maintenance. We can use commands similar to npm run dev
and npm run build
to compile the front-end code and place the compilation results in Laravel's public directory so that we can view them through the browser Access the application directly.
The following is a simple example to demonstrate the implementation of this method:
2.1 Create a new Laravel project
First, we need to create a new Laravel project in the command line Laravel Project:
composer?create-project?--prefer-dist?laravel/laravel?blog
2.2 Install Node.js and NPM
In the next steps, we need to install Node.js and NPM.
In Ubuntu, you can use the following command to install:
sudo?apt-get?install?nodejs sudo?apt-get?install?npm
2.3 Install Laravel Mix in Laravel
Then, we need to install Laravel Mix:
npm?install?--save-dev?laravel-mix
Then, we need to execute the following command to generate the webpack.mix.js
configuration file:
node_modules/.bin/mix
2.4 Write the front-end code
Next, we need to write the front-end code. For example, we can write some JavaScript code in the resources/assets/js/app.js
file. The following is a simple example:
"use?strict"; window.Vue?=?require('vue'); Vue.component('example-component',?require('./components/ExampleComponent.vue')); const?app?=?new?Vue({ ????el:?'#app' });
2.5 Writing front-end resources
We can put the front-end resource files in the resources/assets
directory. For example, we can write some CSS styles in resources/assets/sass/app.scss
.
html,?body?{ ??height:?100%; ??margin:?0; } #app?{ ??display:?flex; ??align-items:?center; ??justify-content:?center; ??height:?100%; } .title?{ ??font-size:?24px; ??text-align:?center; }
2.6 Configuring Laravel Mix
我們需要在 webpack.mix.js
文件中配置 Laravel Mix。例如,我們可以使用 .sass()
方法來(lái)生成 CSS 文件,并使用 .js()
方法來(lái)生成 JavaScript 文件:
const?mix?=?require('laravel-mix'); mix.js('resources/assets/js/app.js',?'public/js') ???.sass('resources/assets/sass/app.scss',?'public/css');
2.7 編譯前端資源
接下來(lái),我們可以運(yùn)行以下命令來(lái)編譯前端資源:
npm?run?dev
或
npm?run?watch
這樣,我們就可以在瀏覽器中看到我們的應(yīng)用程序了。
- 部署應(yīng)用程序
無(wú)論我們使用哪種方式來(lái)實(shí)現(xiàn)前后端分離,最終都需要進(jìn)行部署。我們可以使用第三方工具如 Jenkins、Capistrano 和 Docker Compose 等來(lái)自動(dòng)化部署。這里介紹一種基于 NGINX + PHP-FPM + MySQL 的部署方式。
3.1 安裝服務(wù)
首先,我們需要安裝 NGINX、PHP-FPM 和 MySQL。我們可以使用以下命令在 Ubuntu 中進(jìn)行安裝:
sudo?apt-get?install?nginx sudo?apt-get?install?mysql-server sudo?apt-get?install?php-fpm
3.2 配置 NGINX
接下來(lái),我們需要配置 NGINX。我們可以在 /etc/nginx/sites-available
目錄下創(chuàng)建一個(gè)新的配置文件。以下是配置文件的示例:
server?{ ????listen?80; ????server_name?yourdomain.com; ????root?/var/www/public; ????index?index.php; ????location?/?{ ????????try_files?$uri?$uri/?/index.php?$query_string; ????} ????location?~?/\.?{ ????????deny?all; ????} ????location?~?\.php$?{ ????????fastcgi_pass?unix:/run/php/php7.4-fpm.sock; ????????fastcgi_split_path_info?^(.+\.php)(/.+)$; ????????include?fastcgi_params; ????????fastcgi_param?SCRIPT_FILENAME?$document_root$fastcgi_script_name; ????????fastcgi_param?PATH_INFO?$fastcgi_path_info; ????????internal; ????} }
我們需要將我們的代碼放置在 /var/www/public
目錄中。例如,我們使用前兩種方式中的第一種方式,代碼存放在了一個(gè) 獨(dú)立的前端項(xiàng)目 中。我們可以使用以下命令將編譯好的前端代碼復(fù)制到 /var/www/public
目錄中:
cp?-r?/path/to/frontend/dist/*?/var/www/public
3.3 配置 MySQL
接下來(lái),我們需要配置 MySQL。我們可以使用以下命令進(jìn)行安全設(shè)置:
sudo?mysql_secure_installation
然后,我們可以創(chuàng)建一個(gè)新的 MySQL 數(shù)據(jù)庫(kù):
CREATE?DATABASE?dbname?CHARACTER?SET?utf8mb4?COLLATE?utf8mb4_unicode_ci; CREATE?USER?'dbuser'@'localhost'?IDENTIFIED?BY?'dbpassword'; GRANT?ALL?PRIVILEGES?ON?dbname.*?TO?'dbuser'@'localhost';
在 Laravel 的 .env
配置文件中,我們需要進(jìn)行如下數(shù)據(jù)庫(kù)配置:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=dbname DB_USERNAME=dbuser DB_PASSWORD=dbpassword
3.4 執(zhí)行數(shù)據(jù)庫(kù)遷移
接下來(lái),我們需要執(zhí)行 Laravel 數(shù)據(jù)庫(kù)遷移,并進(jìn)行一些初始化操作:
php?artisan?migrate php?artisan?db:seed php?artisan?key:generate
3.5 重啟服務(wù)
最后,我們需要重啟 NGINX 和 PHP-FPM 服務(wù),使配置生效:
sudo?systemctl?restart?nginx sudo?systemctl?restart?php7.4-fpm
至此,我們可以通過(guò)瀏覽器訪問(wèn)我們的應(yīng)用程序,Laravel 前后端分離部署就完成了。
三、結(jié)論
本文介紹了使用 Laravel 實(shí)現(xiàn)前后端分離部署的兩種方式:創(chuàng)建一個(gè)新的前端項(xiàng)目和使用 Laravel Mix 打包前端項(xiàng)目?jī)煞N方式。當(dāng)然,對(duì)于前端開(kāi)發(fā)人員來(lái)說(shuō),也可以選擇自己熟悉的框架、編程語(yǔ)言來(lái)進(jìn)行前端開(kāi)發(fā),只需要遵循前后端分離的原則即可??傊?,Laravel 的靈活性使得它可以與許多現(xiàn)代前端框架和工具配合使用,讓開(kāi)發(fā)人員可以更自由地選擇適合自己的開(kāi)發(fā)方式。
The above is the detailed content of How to use Laravel to implement separate deployment of front-end and back-end. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In Laravel, routing is the entry point of the application that defines the response logic when a client requests a specific URI. The route maps the URL to the corresponding processing code, which usually contains HTTP methods, URIs, and actions (closures or controller methods). 1. Basic structure of route definition: bind requests using Route::verb('/uri',action); 2. Supports multiple HTTP verbs such as GET, POST, PUT, etc.; 3. Dynamic parameters can be defined through {param} and data can be passed; 4. Routes can be named to generate URLs or redirects; 5. Use grouping functions to uniformly add prefixes, middleware and other sharing settings; 6. Routing files are divided into web.php, ap according to their purpose

InLaravel,policiesorganizeauthorizationlogicformodelactions.1.Policiesareclasseswithmethodslikeview,create,update,anddeletethatreturntrueorfalsebasedonuserpermissions.2.Toregisterapolicy,mapthemodeltoitspolicyinthe$policiesarrayofAuthServiceProvider.

To create new records in the database using Eloquent, there are four main methods: 1. Use the create method to quickly create records by passing in the attribute array, such as User::create(['name'=>'JohnDoe','email'=>'john@example.com']); 2. Use the save method to manually instantiate the model and assign values ??to save one by one, which is suitable for scenarios where conditional assignment or extra logic is required; 3. Use firstOrCreate to find or create records based on search conditions to avoid duplicate data; 4. Use updateOrCreate to find records and update, if not, create them, which is suitable for processing imported data, etc., which may be repetitive.

Thephpartisandb:seedcommandinLaravelisusedtopopulatethedatabasewithtestordefaultdata.1.Itexecutestherun()methodinseederclasseslocatedin/database/seeders.2.Developerscanrunallseeders,aspecificseederusing--class,ortruncatetablesbeforeseedingwith--trunc

Artisan is a command line tool of Laravel to improve development efficiency. Its core functions include: 1. Generate code structures, such as controllers, models, etc., and automatically create files through make: controller and other commands; 2. Manage database migration and fill, use migrate to run migration, and db:seed to fill data; 3. Support custom commands, such as make:command creation command class to implement business logic encapsulation; 4. Provide debugging and environment management functions, such as key:generate to generate keys, and serve to start the development server. Proficiency in using Artisan can significantly improve Laravel development efficiency.

ToruntestsinLaraveleffectively,usethephpartisantestcommandwhichsimplifiesPHPUnitusage.1.Setupa.env.testingfileandconfigurephpunit.xmltouseatestdatabaselikeSQLite.2.Generatetestfilesusingphpartisanmake:test,using--unitforunittests.3.Writetestswithmeth

Yes,youcaninstallLaravelonanyoperatingsystembyfollowingthesesteps:1.InstallPHPandrequiredextensionslikembstring,openssl,andxmlusingtoolslikeXAMPPonWindows,HomebrewonmacOS,oraptonLinux;2.InstallComposer,usinganinstalleronWindowsorterminalcommandsonmac

Defining a method (also known as an action) in a controller is to tell the application what to do when someone visits a specific URL. These methods usually process requests, process data, and return responses such as HTML pages or JSON. Understanding the basic structure: Most web frameworks (such as RubyonRails, Laravel, or SpringMVC) use controllers to group related operations. Methods within each controller usually correspond to a route, i.e. the URL path that someone can access. For example, there may be the following methods in PostsController: 1.index() – display post list; 2.show() – display individual posts; 3.create() – handle creating new posts; 4.u
