php artisan ui bootstrap

Использование каркаса аутентификации Bootstrap 4 в Laravel 8 вместо Tailwind

Восьмая версия Laravel была встречена с энтузиазмом. Данный выпуск отмечен несколькими радикальными изменениями. Одним из наиболее примечательных, хотя и спорных новшеств стала замена Bootstrap на Jetstream. Laravel Jetstream – каркас аутентификации со стильным дизайном. Скаффолдинг включает два стека для создания системы авторизации:

Оба стека сами по себе прекрасны, но они сильно отличаются от связки Bootstrap и jQuery, к которой привыкло большинство разработчиков. Генерирование системы авторизации на основе Bootstrap в Laravel больше не поддерживается, и к несчастью, разработчикам предстоит изучать новый скаффолдинг.

К счастью, фреймворк Laravel относится к проектам с открытым исходным кодом: любой заинтересованный разработчик имеет возможность создавать свои плагины или интеграции для этой платформы. В этой статье мы рассмотрим способ использования привычного каркаса для аутентификации на основе Bootstrap в Laravel 8.

Создаем новый проект Laravel

Если вы уже установили Laravel Installer (инструкцию по инсталляции можно посмотреть здесь),выполните команду:

Если Laravel еще не установлен, команда будет выглядеть так:

Затем перейдите в каталог с проектом командой:

Устанавливаем Laravel UI

Laravel UI – официальный пакет, предусматривающий генерацию страниц авторизации на основе CSS стилей фреймворка Bootstrap. Последняя редакция Laravel UI поддерживает Laravel 8, что дает нам возможность импортировать страницы аутентификации, контроллеры и другие необходимые компоненты. Для установки Laravel UI выполните приведенную ниже команду:

Добавляем Bootstrap в Laravel

Laravel UI предусматривает три опции для создания каркаса аутентификации: Bootstrap, Vue и React. Нам понадобится Bootstrap. Давайте установим соответствующий компонент с помощью следующей команды:

Обратите внимание, что мы используем параметр auth, который помимо установки Bootstrap и базового каркаса авторизации также добавит генераторы страниц для входа и регистрации.

Устанавливаем нужные пакеты npm

Параметры конфигурации Bootstrap были внесены в файл package.json на предыдущем этапе, теперь все готово к установке npm пакетов. Убедитесь, что Node.js и менеджер пакетов npm установлены в вашей системе, используя следующие команды:

Если все в порядке, устанавливаем пакеты:

Миграция базы данных

С помощью приведенной ниже команды мы создадим таблицы в базе данных:

Запускаем сервер в производство

Мы, наконец, готовы запустить Laravel с поддержкой скаффолдинга на основе Bootstrap: иногда старые технологии лучше новых:

Надеюсь, эта статья вам пригодилась. Трудно сказать, что лучше – Bootstrap или Tailwind. На самом деле это вопрос личных предпочтений. Но поскольку Laravel 8 по умолчанию использует только Tailwind в связке с Livewire или Inertia, это обескураживает разработчиков, привыкших к Bootstrap. После интеграции Bootstrap в Laravel 8 можно работать над проектами, как раньше.

Пожалуйста, опубликуйте свои мнения по текущей теме материала. За комментарии, дизлайки, подписки, лайки, отклики низкий вам поклон!

Источник

Аутентификация в Laravel 6: Установка и настройка

php artisan ui bootstrap. Смотреть фото php artisan ui bootstrap. Смотреть картинку php artisan ui bootstrap. Картинка про php artisan ui bootstrap. Фото php artisan ui bootstrap

В этом уроке мы научимся добавлять аутентификацию в шестую Laravel и сделаем страницы входа, регистрации, выхода и сброса пароля.

В Laravel 6 каркас аутентификации переместили в пакет Laravel/UI, который нужно устанавливать отдельно, используя следующую команду:

Далее вы можете выполнить следующую команду:

Теперь пользователи могут регистрироваться и аутентифицироваться.

Контроллеры аутентификации содержат необходимую логику для аутентификации и создания новых пользователей в базе данных, поэтому вам больше ничего не нужно ничего добавлять в систему. Ну, кроме случаев, когда вы захотите настроить внешний вид или поведение, но об этом мы поговорим позже.

php artisan ui bootstrap. Смотреть фото php artisan ui bootstrap. Смотреть картинку php artisan ui bootstrap. Картинка про php artisan ui bootstrap. Фото php artisan ui bootstrap

Вход в систему будет можно посмотреть по адресу http://localhost:8000/login :

php artisan ui bootstrap. Смотреть фото php artisan ui bootstrap. Смотреть картинку php artisan ui bootstrap. Картинка про php artisan ui bootstrap. Фото php artisan ui bootstrap

Шаблоны загружаются без стилей. Чтобы исправить это, вам нужно установить и собрать фронтенд-зависимости, используя следующие команды:

Теперь страницы должны отображаться правильно:

php artisan ui bootstrap. Смотреть фото php artisan ui bootstrap. Смотреть картинку php artisan ui bootstrap. Картинка про php artisan ui bootstrap. Фото php artisan ui bootstrap

Откройте routes/web.php — он должен выглядеть так:

Метод Auth::routes() включает в себя маршруты для логина, регистрации, логаута и сброса пароля. Этот метод и маршрут home были добавлены вместе с каркасом аутентификации в предыдущем разделе.

LoginController, RegisterController и ResetPasswordController

Как защитить маршруты

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

Метод middleware() может быть вызван либо из контроллера, либо из определения маршрута. Давайте удалим вызов из контроллера. Затем откроем файл routes/web.php и обновим определение маршрута home следующим образом:

Выводы

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

Наш php artisan ui bootstrap. Смотреть фото php artisan ui bootstrap. Смотреть картинку php artisan ui bootstrap. Картинка про php artisan ui bootstrap. Фото php artisan ui bootstrapТелеграм-канал — следите за новостями о Laravel.

Задать вопросы по урокам можно на нашем форуме.

Источник

JavaScript & CSS Scaffolding

Introduction

While Laravel does not dictate which JavaScript or CSS pre-processors you use, it does provide a basic starting point using Bootstrap, React, and / or Vue that will be helpful for many applications. By default, Laravel uses NPM to install both of these frontend packages.

The Bootstrap and Vue scaffolding provided by Laravel is located in the laravel/ui Composer package, which may be installed using Composer:

Once the laravel/ui package has been installed, you may install the frontend scaffolding using the ui Artisan command:

Laravel Mix provides a clean, expressive API over compiling SASS or Less, which are extensions of plain CSS that add variables, mixins, and other powerful features that make working with CSS much more enjoyable. In this document, we will briefly discuss CSS compilation in general; however, you should consult the full Laravel Mix documentation for more information on compiling SASS or Less.

JavaScript

Laravel does not require you to use a specific JavaScript framework or library to build your applications. In fact, you don’t have to use JavaScript at all. However, Laravel does include some basic scaffolding to make it easier to get started writing modern JavaScript using the Vue library. Vue provides an expressive API for building robust JavaScript applications using components. As with CSS, we may use Laravel Mix to easily compile JavaScript components into a single, browser-ready JavaScript file.

Writing CSS

Before compiling your CSS, install your project’s frontend dependencies using the Node package manager (NPM):

The webpack.mix.js file included with Laravel’s frontend scaffolding will compile the resources/sass/app.scss SASS file. This app.scss file imports a file of SASS variables and loads Bootstrap, which provides a good starting point for most applications. Feel free to customize the app.scss file however you wish or even use an entirely different pre-processor by configuring Laravel Mix.

Writing JavaScript

All of the JavaScript dependencies required by your application can be found in the package.json file in the project’s root directory. This file is similar to a composer.json file except it specifies JavaScript dependencies instead of PHP dependencies. You can install these dependencies using the Node package manager (NPM):

By default, the Laravel package.json file includes a few packages such as lodash and axios to help you get started building your JavaScript application. Feel free to add or remove from the package.json file as needed for your own application.

Once the packages are installed, you can use the npm run dev command to compile your assets. Webpack is a module bundler for modern JavaScript applications. When you run the npm run dev command, Webpack will execute the instructions in your webpack.mix.js file:

By default, the Laravel webpack.mix.js file compiles your SASS and the resources/js/app.js file. Within the app.js file you may register your Vue components or, if you prefer a different framework, configure your own JavaScript application. Your compiled JavaScript will typically be placed in the public/js directory.

The app.js file will load the resources/js/bootstrap.js file which bootstraps and configures Vue, Axios, jQuery, and all other JavaScript dependencies. If you have additional JavaScript dependencies to configure, you may do so in this file.

Writing Vue Components

When using the laravel/ui package to scaffold your frontend, an ExampleComponent.vue Vue component will be placed in the resources/js/components directory. The ExampleComponent.vue file is an example of a single file Vue component which defines its JavaScript and HTML template in the same file. Single file components provide a very convenient approach to building JavaScript driven applications. The example component is registered in your app.js file:

Remember, you should run the npm run dev command each time you change a Vue component. Or, you may run the npm run watch command to monitor and automatically recompile your components each time they are modified.

If you are interested in learning more about writing Vue components, you should read the Vue documentation, which provides a thorough, easy-to-read overview of the entire Vue framework.

Using React

If you prefer to use React to build your JavaScript application, Laravel makes it a cinch to swap the Vue scaffolding with React scaffolding:

Adding Presets

Presets are «macroable», which allows you to add additional methods to the UiCommand class at runtime. For example, the following code adds a nextjs method to the UiCommand class. Typically, you should declare preset macros in a service provider:

Then, you may call the new preset via the ui command:

Источник

Php artisan ui bootstrap

This legacy package is a very simple authentication scaffolding built on the Bootstrap CSS framework. While it continues to work with the latest version of Laravel, you should consider using Laravel Breeze for new projects. Or, for something more robust, consider Laravel Jetstream.

While Laravel does not dictate which JavaScript or CSS pre-processors you use, it does provide a basic starting point using Bootstrap, React, and / or Vue that will be helpful for many applications. By default, Laravel uses NPM to install both of these frontend packages.

Only the latest major version of Laravel UI receives bug fixes. The table below lists compatible Laravel versions:

VersionLaravel Version
1.x5.8, 6.x
2.x7.x
3.x8.x

The Bootstrap and Vue scaffolding provided by Laravel is located in the laravel/ui Composer package, which may be installed using Composer:

Once the laravel/ui package has been installed, you may install the frontend scaffolding using the ui Artisan command:

Laravel Mix provides a clean, expressive API over compiling SASS or Less, which are extensions of plain CSS that add variables, mixins, and other powerful features that make working with CSS much more enjoyable. In this document, we will briefly discuss CSS compilation in general; however, you should consult the full Laravel Mix documentation for more information on compiling SASS or Less.

Laravel does not require you to use a specific JavaScript framework or library to build your applications. In fact, you don’t have to use JavaScript at all. However, Laravel does include some basic scaffolding to make it easier to get started writing modern JavaScript using the Vue library. Vue provides an expressive API for building robust JavaScript applications using components. As with CSS, we may use Laravel Mix to easily compile JavaScript components into a single, browser-ready JavaScript file.

Before compiling your CSS, install your project’s frontend dependencies using the Node package manager (NPM):

The webpack.mix.js file included with Laravel’s frontend scaffolding will compile the resources/sass/app.scss SASS file. This app.scss file imports a file of SASS variables and loads Bootstrap, which provides a good starting point for most applications. Feel free to customize the app.scss file however you wish or even use an entirely different pre-processor by configuring Laravel Mix.

All of the JavaScript dependencies required by your application can be found in the package.json file in the project’s root directory. This file is similar to a composer.json file except it specifies JavaScript dependencies instead of PHP dependencies. You can install these dependencies using the Node package manager (NPM):

By default, the Laravel package.json file includes a few packages such as lodash and axios to help you get started building your JavaScript application. Feel free to add or remove from the package.json file as needed for your own application.

Once the packages are installed, you can use the npm run dev command to compile your assets. Webpack is a module bundler for modern JavaScript applications. When you run the npm run dev command, Webpack will execute the instructions in your webpack.mix.js file:

By default, the Laravel webpack.mix.js file compiles your SASS and the resources/js/app.js file. Within the app.js file you may register your Vue components or, if you prefer a different framework, configure your own JavaScript application. Your compiled JavaScript will typically be placed in the public/js directory.

The app.js file will load the resources/js/bootstrap.js file which bootstraps and configures Vue, Axios, jQuery, and all other JavaScript dependencies. If you have additional JavaScript dependencies to configure, you may do so in this file.

Writing Vue Components

When using the laravel/ui package to scaffold your frontend, an ExampleComponent.vue Vue component will be placed in the resources/js/components directory. The ExampleComponent.vue file is an example of a single file Vue component which defines its JavaScript and HTML template in the same file. Single file components provide a very convenient approach to building JavaScript driven applications. The example component is registered in your app.js file:

Remember, you should run the npm run dev command each time you change a Vue component. Or, you may run the npm run watch command to monitor and automatically recompile your components each time they are modified.

If you are interested in learning more about writing Vue components, you should read the Vue documentation, which provides a thorough, easy-to-read overview of the entire Vue framework.

If you prefer to use React to build your JavaScript application, Laravel makes it a cinch to swap the Vue scaffolding with React scaffolding:

Presets are «macroable», which allows you to add additional methods to the UiCommand class at runtime. For example, the following code adds a nextjs method to the UiCommand class. Typically, you should declare preset macros in a service provider:

Then, you may call the new preset via the ui command:

Thank you for considering contributing to UI! The contribution guide can be found in the Laravel documentation.

In order to ensure that the Laravel community is welcoming to all, please review and abide by the Code of Conduct.

Please review our security policy on how to report security vulnerabilities.

Laravel UI is open-sourced software licensed under the MIT license.

Источник

Php artisan ui bootstrap

Laravel Livewire & Bootstrap 5 UI & CRUD starter kit.

Latest commit

Git stats

Files

Failed to load latest commit information.

readme.md

Laravel Livewire & Bootstrap 5 UI & CRUD starter kit. This package is a modernized version of the old laravel/ui package for developers who prefer using Bootstrap 5 and full page Livewire components to build their projects. It also comes with a few features to boost your development speed even more.

This package was designed to work with fresh Laravel projects.

Install Laravel via Valet, Docker, or whatever you prefer:

Require this package via composer:

Run the ui:install command:

Once the installation is complete, you should be able to visit your app URL and login with user@example.com as the email, and password as the password. This was seeded for you to test with.

This command will create your Livewire auth components & views, update your User model & factory, migrate & seed a default User, configure Bootstrap 5 JavaScript & SCSS through NPM/Webpack, create an IDE helper file, and run the necessary NPM commands.

This will make a model with an automatic migration method included. It will also make a factory for the model whose definition points to the model definition method.

This will make CRUD components & views for a given component path/namespace. This includes an index, create, read, update, and delete. It also comes with searching, sorting, and filtering, which is easily customizable inside the index component class.

For making CRUD inside of subfolders, simply use slashes or dot notation:

If the model (e.g. User in the example above) does not already exist when making CRUD, it will ask if you want to make it. After generating CRUD, all you need to do is add your model fields to the component views. Check out the Users component & views that come with the package when you run ui:install for an example.

Running Automatic Migrations

This command goes through your model migration methods and compares their schema’s with the existing database table schema’s. If any changes need to be made, it applies them automatically via Doctrine.

This command works well alongside traditional migration files. When you run this command, it will run your traditional migrations first, and the automatic migrations after. This is useful for cases where you don’t need to couple a database table with a model (pivots, etc.).

This package promotes the usage of automatic migrations.

To use automatic migrations, specify a migration method inside your models:

Or, make a new model via the ui:model command, which will include a migration method for you:

This package also promotes the usage of automatic routing.

To use automatic routing, specify a route method inside your full page Livewire components:

The route method returns the Laravel Route facade, just like you would use in route files. This means that your component route can do anything a normal Laravel route can do. These routes are registered through the package service provider automatically, so you’ll no longer have to manage messy route files.

Automatic Attribute Hashing

The HasHashes traits allows you to specify model attributes you want to hash automatically when they are saving to the database.

To use automatic hashing, use the HashHashes trait and specify a hashes property with the attributes that should be automatically hashed:

This trait will only automatically hash attribute values that are not already hashed, so it will not slow down seeders.

Form Data Manipulation

Binding Model Data

If you’re using your own HTML inputs, make sure you prepend model. to the wire:model.* attribute:

Getting Model Data

Getting all model data as an array:

Getting an array of data:

Getting a single value:

You can specify a default value via the second parameter, or omit it entirely.

Setting Model Data

Setting an array of values:

Setting a single value:

Resetting Model Data

You can reset all model data easily:

Validating Model Data

You can use it alongside a rules method:

Or by itself, with rules passed directly:

Dynamic Bootstrap Modals

This package allows you to show Livewire components as modals dynamically by emitting a simple event. No more having to manage modal components everywhere in your views.

This will create a partial Livewire component and a view that contains the Bootstrap modal classes.

To show modals, just emit the showModal event.

You can emit this from your component views:

Or from the component classes themselves:

Notice that the second parameter is using the Livewire component class alias. So in this example, auth.password-change actually points to the Auth\PasswordChange component.

Passing Mount Parameters

You can pass any parameters you want to your modal component mount method by specifying them in the showModal event:

Passing parameters via component views:

Or from a component class:

Now, in our component mount method, we can use this parameter:

Notice how even model binding works here. If you need to pass more than one parameter, just keep adding them to the showModal emit, separated by a comma.

Hide the currently open modal via the hideModal event:

Or, through component classes:

You can also hide the modal through regular Bootstrap data-bs-toggle buttons:

This package comes with some handy Blade components, ensuring that you stay DRY, while keeping your markup nice and neat.

If lazy and debounce are not used, defer is the default.

The lazy and debounce props work the same as the input component.

The options array can be an indexed or associative array. If the array is associative, the array keys will be used for the option values, and the array values will be used for the option labels. If the array is indexed, it’s values will be used for both the option values and labels.

The options array works the same as the select component.

A dropdown item button:

A CRUD action button:

Responsive pagination links:

A Font Awesome icon:

Font Awesome Icons

When running the ui:install command, you are given the option to install Font Awesome free or pro. If you select pro, you are required to have a global NPM token configured.

For information on how to configure this token, please see the Font Awesome documentation.

Publish the package config, stubs, and views via the vendor:publish command:

Using Custom Stubs

Once you have published the package config and stub files, the stubs will be located in the resources/stubs/vendor/ui folder.

Update the config/ui.php file and point the stub_path to this path:

The commands will now use this path for the stubs. Customize them to your needs.

About

Laravel Livewire & Bootstrap 5 UI & CRUD starter kit.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *