Laravel framework russian community


Every Page component is a Vue component but Nuxt.js adds special attributes and functions to make the development of your universal application as easy as possible.

Attribute Description Documentation
The most important key. It can be asynchronous and receives the context as argument. Guide: Async data
Used to fill the store before rendering the page. It’s like the method, except it doesn’t set the component data. API Pages
Set specific tags for the current page. API Pages
Specify a layout defined in the directory. API Pages
If set to , prevents a page from automatically calling as you enter it and as you leave it, allowing you to manually control the behavior, as this example shows. Only applies if is also set in . API Configuration
Defines a specific transition for the page. API Pages
Boolean (default: ). Specify if you want the page to scroll to the top before rendering the page. It’s used for .
Validator function for .
Defines middleware for this page. The middleware will be called before rendering the page.

More information about the pages properties usage: API Pages

Запрос и ответ

Когда вы создаете Slim-приложение, вы часто работаете непосредственно с объектами Request and Response. Эти объекты представляют собой фактический HTTP-запрос, полученный веб-сервером, и возможный HTTP-ответ, возвращаемый клиенту.

Каждому маршруту Slim-приложения присваиваются текущие объекты Request and Response в качестве аргументов его подпрограммы обратного вызова. Эти объекты реализуют популярные интерфейсы PSR 7. Slim route приложения может проверять или манипулировать этими объектами по мере необходимости. В конечном счете, каждый маршрут приложения Slim MUST возвращать ответ PSR 7 объекта.


The method, if set, is called every time before loading the component (only for page components). It will be called server-side once (on the first request to the Nuxt app) and client-side when navigating to further routes.

The method receives the object as the first argument, we can use it to fetch some data and fill the store. To make the method asynchronous, return a Promise, Nuxt.js will wait for the promise to be resolved before rendering the component.

Warning: You don’t have access to the component instance through inside because it is called before initiating the component.

Example of :

You can also use / to make your code cleaner:

Listening to query string changes

The method is not called on query string changes by default. If you want to change this behavior, for example when building a pagination component, you can setup parameters that should be listened to through the property of your page component. Learn more on the API page.

Illustrating the Flow of Control

Let’s look at a stripped-down example with some middleware that writes log messages to the standard output stream in your terminal:

File: main.go

Run this application and make a request to http://localhost:3000. You should see some log output similar to this:

It’s clear to see how control is being passed through the handler chain in the order we nested them, and then back up again in the reverse direction.

We can stop control propagating through the chain at any point by issuing a from a middleware handler.

In the example above I’ve included a conditional return in the function. Try it by visiting http://localhost:3000/foo and checking the log again – you’ll see that this time the request gets no further than before passing back up the chain.

What is a Middleware?

Middleware is a term used by different web frameworks that allow you to hook into the typical request processing flow of an application. During a typical request life cycle, when someone enters your application they use the URL which web frameworks map to a route.

A middleware provides an extra layer between the request and response.

In Laravel, we use the term middleware but different languages and frameworks use different terms to implement the same concept. For example, in Laravel, Ruby on Rails and NodeJS we use the term middleware while in Java world, it’s called filters and in C# language calls it delegate handlers.

Upading Laravel Migration for User

Next we will update our User migration file which is located in folder. Open the file and add a new field in it like below:

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

class CreateUsersTable extends Migration
     * Run the migrations.
     * @return void
    public function up()
        Schema::create('users', function (Blueprint $table) {

     * Reverse the migrations.
     * @return void
    public function down()

Open the terminal and run the below command to migrate all tables to the database.

php artisan migrate

Dynamic Routes

To define a dynamic route with a parameter, you need to define a .vue file OR a directory prefixed by an underscore.

This file tree:

will automatically generate:

As you can see the route named has the path which makes it optional, if you want to make it required, create an file in the directory instead.

As of Nuxt >= v2.13 there is a crawler installed that will now crawl your link tags and generate your routes when using the command based on those links.

Warning: If you using Nuxt >= v2.13 and have pages that have no links such as secret pages and you would like these to also be generated then you can use the property.

Warning: dynamic routes are ignored by the command when using Nuxt <= v2.12

Validate Route Params

Nuxt.js lets you define a validator method inside your dynamic route component.

In this example:

If the validate method does not return or a that resolve to , or throws an Error, Nuxt.js will automatically load the 404 error page or 500 error page in case of an error.

More information about the validate method: API Pages validate

Terminable Middleware

Sometimes a middleware may need to do some work after the HTTP response has already been sent to the browser. For example, the «session» middleware writes the session data to storage after the response has been sent to the browser. To accomplish this, define the middleware as «terminable» by adding a method to the middleware:

The method should receive both the request and the response. Once you have defined a terminable middleware, you should add it to the list of global middleware in your file.

When calling the method on your middleware, Lumen will resolve a fresh instance of the middleware from the service container. If you would like to use the same middleware instance when the and methods are called, register the middleware with the container using the container’s method.

How does middleware work?

Different frameworks use middleware differently. Slim adds middleware as concentric layers surrounding your core application. Each new middleware layer surrounds any existing middleware layers. The concentric structure expands outwardly as additional middleware layers are added.

The last middleware layer added is the first to be executed.

When you run the Slim application, the Request and Response objects traverse the middleware structure from the outside in. They first enter the outer-most middleware, then the next outer-most middleware, (and so on), until they ultimately arrive at the Slim application itself. After the Slim application dispatches the appropriate route, the resultant Response object exits the Slim application and traverses the middleware structure from the inside out. Ultimately, a final Response object exits the outer-most middleware, is serialized into a raw HTTP response, and is returned to the HTTP client. Here’s a diagram that illustrates the middleware process flow:

Using Parameters with Middlewares

When using Laravel Middleware in your web application, you might want to pass a parameter to middleware class. A very good example could be a role middleware. Let’s assume we have a role middleware and we would like to check within our middleware which role current users have and based on that role we perform some actions.

For using the parameters in our Admin middleware, we can pass the third parameter after and like below.

Before using this example, you should have a Role model which have a relationship to the User model. Then create a new middleware called Role and update it’s method like below.

 * Handle an incoming request.
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @param $role
 * @return mixed
public function handle($request, Closure $next, $role)
    if(auth()->user()->hasRole() == 'admin'){
        return $next($request);

    return redirect('home')->with('error','You are not authorised to access admin pages.');

Now we will update the middleware method on our route like below.

Route::get('/admin', '')->name('admin')->middleware('role:admin');

Начальная настройка приложения

Самый простой способ начать работу с Nuxt.js — это использовать шаблон, созданный командой Nuxt. Мы можем быстро установить его в наш проект (ssr-blog), используя vue-cli:

vue init nuxt/starter ssr-blog

После того, как вы запустите эту команду, откроется приглашение и вам будут заданы несколько вопросов. Вы можете нажать Return, чтобы принять ответы по умолчанию, или ввести свои собственные значения.

Примечание. Если у вас не установлена vue-cli, для ее установки необходимо сначала запустить npm install -g @vue/cli.

Далее мы устанавливаем зависимости проекта:

cd ssr-blog
npm install

Теперь мы можем запустить приложение:

npm run dev

Если все пойдет хорошо, вы сможете перейти на http://localhost:3000 и увидеть начальную страницу шаблона Nuxt.js. Вы даже можете просмотреть исходники страницы, чтобы увидеть, что весь контент, сгенерированный на странице.

Далее нам нужно сделать несколько простых настроек в файле nuxt.config.js:

// ./nuxt.config.js

module.exports = {
   * Headers of the page
  head: {
    titleTemplate: '%s | Awesome JS SSR Blog',
    // ...
    link: [
      // ...
        rel: 'stylesheet',
        href: ''
  // ...

В приведенном выше файле конфигурации мы просто указываем шаблон заголовка, который будет использоваться для всего приложения, с помощью опции titleTemplate.

Мы также подключили мой текущий CSS-фреймворк, Bulma, чтобы воспользоваться некоторыми предустановленными стилями. Это было сделано через опцию link.

Примечание. Nuxt.js использует vue-meta для обновления заголовков и атрибутов HTML приложений.

Теперь мы можем сделать следующие несколько шагов, добавив страницы и функции нашего блога.

Работа с макетами страниц (Page Layouts)

Во-первых, мы определим пользовательский базовый макет для всех наших страниц. Мы можем расширить основной макет Nuxt.js, обновив файл layouts/default.vue:

<!-- ./layouts/default.vue -->

    <!-- navigation -->
    <nav class="navbar has-shadow" role="navigation" aria-label="main navigation">
      <div class="container">
        <div class="navbar-start">
          <nuxt-link to="/" class="navbar-item">
            Awesome JS SSR Blog!
          <nuxt-link active-class="is-active" to="/" class="navbar-item is-tab" exact>Home</nuxt-link>
          <nuxt-link active-class="is-active" to="/about" class="navbar-item is-tab" exact>About</nuxt-link>
    <!-- /navigation -->

    <!-- displays the page component -->


  .main-content {
    margin: 30px 0;

В нашем пользовательском базовом макете мы добавли заголовок навигации сайта. Мы используем компонент <nuxt-link> для создания ссылок на маршруты, которые мы хотим иметь в нашем блоге. Вы можете прочитать документацию, если нужно узнать больше, о том как работает <nuxt-link>.

Компонент <nuxt> действительно очень важен при создании макета, так как именно он отображает компонент страницы.

Также здесь возможно сделать еще несколько вещей — например, определить пользовательские шаблоны документов и схемы ошибок — но мы не будем это делать так как они не нужны для нашего простого блога. Я призываю вас ознакомиться с документацией Nuxt.js по представлениям, чтобы узнать обо всех возможностях.

Как добавить middleware?

Вы можете добавить промежуточное программное обеспечение в Slim-приложение, на индивидуальный маршрут Slim или в группу маршрутов. Все сценарии принимают одно и то же middleware и реализуют один и тот же интерфейс middleware.

Application middleware

Для каждого входящего HTTP-запроса вызывается middleware. Добавьте промежуточное программное обеспечение приложения с помощью метода экземпляра Slim. В этом примере добавляется пример Closure middleware:

Это вывело бы это тело ответа HTTP:

Route middleware

Route middleware вызывается только в том случае, если его маршрут соответствует текущему методу HTTP-запроса и URI. Route middleware указывается сразу же после вызова любого из методов маршрутизации Slim-приложения (например или ). Каждый метод маршрутизации возвращает экземпляр , и этот класс предоставляет тот же интерфейс middleware что и экземпляр приложения Slim. Добавьте middleware в маршрут с помощью метода экземпляра Route. В этом примере добавляется пример Closure middleware:

Это вывело бы это тело ответа HTTP:

Групповое Middleware

В дополнение к общему приложению и стандартным маршрутам, способным принимать middleware, функция определения нескольких маршрутов, также позволяет индивидуальные маршруты внутри. Маршрутное групповое middleware вызывается только в том случае, если его маршрут соответствует одному из определенных методов HTTP-запроса и URI из группы. Чтобы добавить промежуточное программное обеспечение в обратном вызове и промежуточное ПО всей группы, можно установить путем цепочки после метода.

Пример приложения, используя callback middleware в группе обработчиков URL-адресов

При вызове метода будет выводиться строка, подобная приведенной ниже

посещение будет выводить строку, подобную приведенной ниже

но посещение (domain-root), должно было бы генерировать следующий результат, поскольку не было назначено middleware

Передача переменных из middleware

Самый простой способ передать атрибуты из промежуточного программного обеспечения — использовать атрибуты запроса.

Установка переменной в middleware:

Получение переменной в обратном вызове маршрута:

  • Концепции: PSR 7
  • Концепции: Контейнер зависимости

Defining Middleware

To create a new middleware, copy the that is included with the default Lumen application. In our new middleware, we will only allow access to the route if the supplied is greater than 200. Otherwise, we will redirect the users back to the «home» URI.

As you can see, if the given is less than or equal to , the middleware will return an HTTP redirect to the client; otherwise, the request will be passed further into the application. To pass the request deeper into the application (allowing the middleware to «pass»), simply call the callback with the .

It’s best to envision middleware as a series of «layers» HTTP requests must pass through before they hit your application. Each layer can examine the request and even reject it entirely.

Before / After Middleware

Whether a middleware runs before or after a request depends on the middleware itself. For example, the following middleware would perform some task before the request is handled by the application:

However, this middleware would perform its task after the request is handled by the application:

#Seven Examples

If your head boiled from reading the above section, imagine what it was like to write it. This section is meant to be a relaxation for you and me, and will help get your gears turning.

Each function below is a valid Redux middleware. They are not equally useful, but at least they are equally fun.


constlogger=store=>next=>action=>{‘dispatching’, action)

let result =next(action)

console.log(‘next state’, store.getState())


return result






console.error(‘Caught an exception!’, err)




state store.getState()



throw err







const timeoutId =setTimeout(()=>next(action), action.meta.delay)






const queuedActions =

let frame =null


frame =null











frame =requestAnimationFrame(loop)










queuedActions = queuedActions.filter(a=> a !== action)





if(typeof action.then!==’function’){









functionmakeAction(ready, data){

const newAction =Object.assign({}, action,{ ready }, data)

delete newAction.promise

return newAction



return action.promise.then(

result=>next(makeAction(true,{ result })),

error=>next(makeAction(true,{ error }))




typeof action ===’function’

?action(store.dispatch, store.getState)


const todoApp =combineReducers(reducers)

const store =createStore(













Nuxt.js uses the component to let you create amazing transitions/animations between your routes.

Global Settings

Info: Nuxt.js default transition name is .

To add a fade transition to every page of your application, we need a CSS file that is shared across all our routes, so we start by creating a file in the folder.

Our global css in :

Then we add its path to the array in our file:

More information about the transition key: API Configuration transition

Page Settings

You can also define a custom transition for a specific page with the property.

We add a new class in our global css in :

Then we use the transition property to define the class name to use for this page transition:

More information about the transition property: API Pages transition


HTTP middleware provide a convenient mechanism for filtering HTTP requests entering your application. For example, Lumen includes a middleware that verifies if the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to the login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application.

Of course, additional middleware can be written to perform a variety of tasks besides authentication. A CORS middleware might be responsible for adding the proper headers to all responses leaving your application. A logging middleware might log all incoming requests to your application.

All middleware should be stored in the directory.

Build-only Modules

Usually, modules are only required during development and build time. Using helps to make production startup faster and also significantly decreasing size for production deployments. If you are a module author, It is highly recommended to suggest users installing your package as a and use instead of for .

Your module is a unless:

  • It is providing a serverMiddleware
  • It has to register a Node.js runtime hook (Like sentry)
  • It is affecting vue-renderer behavior or using a hook from or namespace
  • Anything else that is outside of webpack scope (Hint: plugins and templates are compiled and are in webpack scope)

NOTE: If you are going to offer using please mention that this feature is only available since Nuxt v2.9. Older users should upgrade Nuxt or use the section.

How do I add middleware?

You may add middleware to a Slim application, to an individual Slim application route or to a route group. All scenarios accept the same middleware and implement the same middleware interface.

Application middleware

Application middleware is invoked for every incoming HTTP request. Add application middleware with the Slim application instance’s method. This example adds the Closure middleware example above:

This would output this HTTP response body:

Route middleware

Route middleware is invoked only if its route matches the current HTTP request method and URI. Route middleware is specified immediately after you invoke any of the Slim application’s routing methods (e.g., or ). Each routing method returns an instance of , and this class provides the same middleware interface as the Slim application instance. Add middleware to a Route with the Route instance’s method. This example adds the Closure middleware example above:

This would output this HTTP response body:

Group Middleware

In addition to the overall application, and standard routes being able to accept middleware, the multi-route definition functionality, also allows individual routes internally. Route group middleware is invoked only if its route matches one of the defined HTTP request methods and URIs from the group. To add middleware within the callback, and entire-group middleware to be set by chaining after the method.

Sample Application, making use of callback middleware on a group of url-handlers

When calling the method, this would output a string similar to the below

visiting would output a string similar to the below

but visiting (domain-root), would be expected to generate the following output as no middleware has been assigned

Passing variables from middleware

The easiest way to pass attributes from middleware is to use the request’s attributes.

Setting the variable in the middleware:

Getting the variable in the route callback:

Grouped Middlewares

Laravel Middlewares provide an intutive way to group bunch of middlewares togather and you can assign all of them to a single key. To groupe multiple middlewares, we use the property in the file. This property takes a key-value pair array. By default Laravel provides a web and api group for middlewares.

 * The application's route middleware groups.
 * @var array
protected $middlewareGroups = [
    'web' => [
        // \Illuminate\Session\Middleware\AuthenticateSession::class,

    'api' => ,

Laravel Middleware Use Cases

Usage of middleware depends on the nature of applications, some middlewares are passive in their nature like logging middleware. Using middlewares we can change/transform the HTTP headers or can execute some custom business logic functions.

Here are some use cases in the Laravel framework, where middleware is used mostly.

  • Changing site language or locale based on the incoming request.
  • Enabling maintenance mode on your application.
  • Rate-limiting a service request.
  • Writing logs.
  • Tracking the application users.
  • Authorizing certain part of your application to only certain users.
  • Checking for bot traffic.

Laravel ships with some pre-built middleware such as there is a middleware to check for the site maintenance mode, another one is which check and sanitize the input request parameters.

I hope you now have a clear understanding about the Laravel Middleware concept if not, don’t worry in the coming section we will create some custom middleware which will help you to understand how we can use middlewares in a real-world application.

Module package commands


Starting in , you can add custom nuxt commands through a Nuxt module’s package. To do so, you must follow the API when defining your command. A simple example hypothetically placed in looks like this:

A few things of note here. First, notice the call to to retrieve the Node executable. Also notice that ES module syntax can’t be used for commands unless you manually incorporate into your code.

Next, you’ll notice how is used to specify the settings and behavior of the command. Options are defined in , which get parsed via . Once arguments are parsed, is automatically called with the instance as first parameter.

In the example above, is used to retrieve parsed command-line arguments. There are more methods and properties in — documentation on them will be provided as this feature is further tested and improved.

To make your command recognizable by the Nuxt CLI, list it under the section of your package.json, using the convention, where relates to your package’s name. With this central binary, you can use to further parse more for your command if you desire.

Once your package is installed (via NPM or Yarn), you’ll be able to execute on the command-line.

There are way more hooks and possibilities for modules. Please read the Nuxt Internals to find out more about the nuxt-internal API.

Common Snippets

Top level options

Sometimes it is more convenient if we can use top level options while registering modules in . This allows us to combine multiple option sources.



Provide plugins

It is common that modules provide one or more plugins when added. For example bootstrap-vue module would require to register itself into Vue. In such situations we can use the helper.



Template plugins

Registered templates and plugins can leverage to conditionally change registered plugins output.



Add a CSS library

If your module will provide a CSS library, make sure to perform a check if the user already included the library to avoid duplicates, and add an option to disable the CSS library in the module.


We can register webpack plugins to emit assets during build.


С этим читают