#laravel 5.7 middleware auth
Explore tagged Tumblr posts
airman7com · 5 years ago
Text
Laravel 5.7 Middleware – Create Custom Middleware with Example
Laravel 5.7 Middleware – Create Custom Middleware with Example
In this laravel middleware tutorial, we will learn how to create custom middleware and how to use it in laravel-based projects. Just create one special middleware and check the language in the query string. And this example also works with version 5.8.
Simply laravel, middleware filters all http requests in laravel-based projects. For example when a user makes any request, the middleware checks

View On WordPress
0 notes
php-sp · 5 years ago
Text
Vanguard - Advanced PHP Login and User Management
New Post has been published on https://intramate.com/php-scripts/vanguard-advanced-php-login-and-user-management/
Vanguard - Advanced PHP Login and User Management
Tumblr media
LIVE PREVIEWGet it now for only $35
Tumblr media
Vanguard is PHP application, written in Laravel PHP framework, that allows website owners to quickly add and enable authentication, authorization and user management to their website. It is designed following latest security and code standards and it is ready for high availability websites. Although it is written in Laravel, it can be used to provide secure login, authentication, authorization and complete user management for any PHP powered website. Vanguard also comes with fully documented JSON API which allows you to easily authenticate users from your mobile (or any other) application.
It comes with almost three hundred automated tests (functional and unit), that cover all vital parts of the application and the API and ensures it’s maintainability and stability.
Version 5.0.1
Features
Secure user registration and login
Social Authentication using Facebook, Twitter and Google+
Password reset
Two-Factor Authentication
Remember Me feature on login
Login with email or username
Google reCAPTCHA on registration
Authentication Throttling (lock user account after few incorrect login attempts)
Interactive Dashboard
Unlimited number of user roles
Powerful admin panel
Unlimited number of permissions
Manage permissions from admin interface
Assign permission to roles
Easily check if user has permission to perform some action
JSON API to build any kind of applications around Vanguard
Super easy installation using installation wizard
User Activity Log
Avatar upload with crop feature
Built using Bootstrap 4
Active Sessions Management (see and manage all your active sessions)
Admins can impersonate users
Full unicode support
Client side and server side form validation
Fully customisable from settings section
Complete and detailed documentation
Fully object oriented and commented PHP and JavaScript code.
Localization support – Translate the application to any language (English, Serbian and German translations included)
Runs on PHP 7.2.5+
Flexible Plugin System
Security
CSRF Protection – all forms include CSRF token
Session Protection – highly secure Laravel session mechanism
Highly secure one-way password hashing
Server Requirements
PHP >= 7.2.5
BCMath PHP Extension
OpenSSL PHP Extension
PDO PHP Extension
Mbstring PHP Extension
Tokenizer PHP Extension
Ctype PHP Extension
XML PHP Extension
JSON PHP Extension
GD PHP Extension
Fileinfo PHP Extension
Demo and Documentation
Demo link: https://demo.vanguardapp.io
Admin Credentials
Username: admin
Password: admin123
Documentation and Support: https://milos.support-hub.io/
Discount Notifications
Subscribe to receive notifications about discounts and updates: https://vanguardapp.io/#subscribe
Changelog
Check the docs for upgrade guide.
April 8, 2020 – Version 5.0.1
Fixed installation wizard
April 5, 2020 – Version 5.0.0
Fixed custom login redirect issue Upgraded to Laravel 7 Switched to Laravel Sanctum for API authentication Replaced API transformers with Laravel's API Resources Changed API response format
September 16, 2019 – Version 4.0.1
Fixed password reset email issue Fixed avatar upload issue Updated registration and email verification flow
September 13, 2019 – Version 4.0.0
Added Plugin Support Upgraded to Laravel 6
April 1, 2019 – Version 3.2.1
Fix installation issue
March 30, 2019 – Version 3.2.0
Upgraded to Laravel 5.8 Replaced deprecated Larvel str_ and array_ helper functions
October 30, 2018 – Version 3.1.0
Upgraded to Laravel 5.7 Fixed issue with API when country_id field is null Fixed Notifications Settings update bug Improved Two-Factor Authentication by adding one more step for phone verification Added Impersonate feature
June 14, 2018 – Version 3.0.1
Minor bug-fix release to address a few mostly UI related bugs. List of changed files available inside the upgrade guide.
May 17, 2018 – Version 3.0.0
Complete frontend re-write with Bootstrap 4 Remove additional step for Twitter authentication since Twitter can provide an email now Update sizes of the avatars retreived during social authentication
March 13, 2018 – Version 2.2.0
Upgrade to Laravel 5.6 Fix issue with Authy secret key and config caching Fix issues with registration history chart Fix installation issue on PHP 7.2
December 19, 2017 – Version 2.1.1
Added ability to configure dates format across the app Added automatic session invalidation and log out of the user if he is banned by the administrator Added device info on session list page Updated dashboard chart to display data in last 365 days (instead of for current year) Extracted model factories to different files (important for testing purposes only) Fixed autoload include issue for existing websites
November 08, 2017 – Version 2.1.0
Upgrade Laravel to version 5.5 Fix glitch on User Acivity search
September 14, 2017 – Version 2.0.2
Fix avatar update issue when admin is updating avatar for some other user Disable API authentication for banned and unconfirmed users Fix country update issue which occures on some MySQL versions
August 25, 2017 – Version 2.0.1
Fix installation issues from previous version Update documentation
August 23, 2017 – Version 2.0.0
Add fully tested JSON API Fix some minor glitches related to translation
May 1, 2017 – Version 1.3.3
Fix incompatibility issues between laravel-jsvalidation package and Laravel Framework version 5.4.19+ Fix issue where country is set to null after user logs in
April 12, 2017 – Version 1.3.2
Removed zizaco/entrust package and replaced with Vanguard's native mechanism for handling roles and permissions $user->can() method now use Laravel's default authorization mechanism. For checking if user has permission defined by Vanguard, you should use $user->hasPermission('...').
March 06, 2017 – Version 1.3.1
Fixed installation issue Fixed issue with FORCE_SSL
February 18, 2017 – Version 1.3.0
Laravel 5.4 upgrade IMPORTANT: Fixed potential security issue with user avatar upload Fixed issue to don't allow banned users to log in via social networks Expanded and updated automated tests to cover all bugs and issues from above
September 30, 2016 – Version 1.2.1
Fixed bug when creating/updating users from admin panel without selected country Fixed small typos on delete user confirmation popup
September 27, 2016 – Version 1.2.0
Updated to Laravel 5.3 InnoDB is now forced storage engine for MySQL database Slightly improved design E-Mail templates updated (now using Laravel 5.3 Notifications feature) Fixed default country value Fixed n+1 problem for activity page (added missing eager loading) Fixed translation glitches Added IIS configuration file PHP 5.6.4 is now minimum PHP version required (Laravel 5.3 requirement) PHP XML extension is now requirement (Laravel 5.3 requirement) Updated and extended documentation Dropped support for HHVM, since Laravel 5.3 does not support it
March 30, 2016 – Version 1.1.2
Add missing middleware to redirect user to install page if Vanguard is not installed
March 29, 2016 – Version 1.1.1
Added German translation files Add translation for few missed strings Fix some small bugs
March 15, 2016 – Version 1.1.0
Add localization support Use social network profile image as default avatar after social auth Fix problems with pagination while browsing search results for users and activities Handle missing email from non-twitter social provider
February 18, 2016 – Version 1.0.4
Updated documentation Added option to allow redirect to custom page after login Disable access to login page for authenticated users
February 4, 2016 – Version 1.0.3
Updated documentation Fixed css glitches Added more tests
January 25, 2016 – Version 1.0.2
New design for error pages Updated installer to require Fileinfo extension
January 22, 2016 – Version 1.0.1
Add missing configuration placeholder file
January 21, 2016 – Version 1.0.0
First release
LIVE PREVIEWGet it now for only $35
0 notes
tak4hir0 · 6 years ago
Link
はじめに 皆様こんにちは。OPTiM新卒1幎目゚ンゞニアの青朚です。 前回は早抌しボタンなんかを䜜っおいたした。 tech-blog.optim.co.jp 今回は、PHP フレヌムワヌクの Laravel を、PostgreSQL ず Vue.js ず組み合わせお䜜成する TODO アプリを通しお玹介したす。 このフレヌムワヌクらはこちらの蚘事でも密かに利甚しおいたす。 tech-blog.optim.co.jp OPTiMではあたり利甚されおいたせんが、䞀郚のアプリケヌションで実利甚されおいる箇所もございたす。 PHPは昔のむメヌゞからかなり避けられおいおいたすが...今のPHPずそのフレヌムワヌクはすごく発展しおいおずおも䜿いやすいので是非䜿っおいただきたいずいう気持ちがありたす。 ですが、珟状はあたり利甚しおいただけなくお個人的には悲しい気持ちでいっぱいです。 そんなPHPですが、フレヌムワヌクLaravelやFuelPHPなどを利甚するこずにより未利甚時よりも高速か぀安党に開発するこずができたす。 そんなフレヌムワヌクの玹介を「TODOリストアプリケヌション」を䜜りながら芋おいきたしょう。 PHPフレヌムワヌク「Laravel」 今回ご玹介するのはPHPフレヌムワヌクの「Laravel」です。 Laravel - The PHP Framework For Web Artisans laravel.jp フレヌムワヌクの仕様に乗っかっお開発するこずによりかなり安党で可甚性のあるアプリケヌションの開発が容易になりたす。 個人的にLaravelのいいずころはズバリ 爆速安党開発 です。 本圓に手早くWebアプリケヌションが䜜れたす。 今たで数人で䜜業しおいたものをたった䞀人で1週間もあればかなり匷い物が䜜れたす 2019幎8月5日珟圚のLaravel最新バヌゞョンは「5.8」で「5.7」のマむナヌアップデヌトずなっおいたす。 Laravelは奇数バヌゞョンがメむンずなっおおり、䞭でもLTSずなっおいるのは「5.1」「5.5」ずなっおいたす。セキュリティフィックス期限はLTSで3幎間、䞀般的なリリヌスに぀いおは1幎間のサポヌトずメンテナンスがされおいたす。 このように、蚀語仕様だけではカバヌできないセキュリティの担保もフレヌムワヌクが担っおくれるこずᅵᅵより、PHP5以前の時代よりも遥かに匷くなっおいたす。 ここで、Googleトレンドより泚目床を比范しおみたしょう。 実は代衚的なWebフレヌムワヌクの「Ruby on Rails」や「Django」などよりもLaravelの泚目床が䞊がっおきおいたす。 日本ではダントツで「Ruby on Rails」が倚く芋られたす。 海倖での「Laravel」の泚目床が䞊がっおきおいるようですね。 Laravelは機胜がずおも豊富です。ですからファむルサむズ的にも倧きくなりたすし、環境にも負担がかかっおしたいたす。 そんな時は「Lumen」を利甚したしょう。ここではあたり解説したせんが、「Lumen」は「Laravel」の軜量版ずしお開発されおいたす。 ずっおも雑に説明するずNode.jsのExpressのような感じですね。 さお、前眮きが長くなりたしたが、本題に移りたいず思いたす。 今回の目暙 PHPフレヌムワヌクLaravelで、DBを䜿甚したSPASingle Page ApplicationのTODOアプリを䜜りたす。 たたログむン認蚌によるナヌザ管理も同時に行っおいきたす。 完成圢 この蚘事の最埌にはこのようなアプリケヌションが出来䞊がりたす。 ナヌザの新芏登録・ログむン・ログアりト ログむンナヌザごずのTODOの衚瀺・远加・曎新・削陀 最䜎限のView 䜿甚する技術 PHP Laravel Vue.js PostgreSQL Docker 導入・環境構築 PHPの導入 LaravelでバヌゞョンごずにPHPに察する芁件が決められおいたす。 珟時点でのPHPの最新バヌゞョンは「7.3.8」 珟時点でのLaravelの最新バヌゞョンは「5.8.17」 Laravel「5.8.*」で求められるPHPの芁件は以䞋のずおりです。 = 7.1.3 BCMath PHP拡匵 Ctype PHP拡匵 JSON PHP拡匵 Mbstring PHP拡匵 OpenSSL PHP拡匵 PDO PHP拡匵 Tokenizer PHP拡匵 XML PHP拡匵 これに応じおPHPの導入を行いたしょう。 ちなみにHomebrewでむンストヌルした堎合は「7.3.7」がむンストヌルされたした。こちらのバヌゞョンでも芁件を満たしおおりたすので倧きな問題はありたせん。 ※ただしセキュリティ等の関係䞊最新バヌゞョンを䜿うに越したこずはありたせん。䞋調べは慎重にか぀念入りに行いたしょう。 Composerの導入 Laravelを構築するためのパッケヌゞマネヌゞャが必芁ずなりたす。 PHPの代衚的なパッケヌゞマネヌゞャである「Composer」を導入したしょう。 curl -sS https://getcomposer.org/installer | php sudo mv composer.phar /usr/local/bin/composer composer config -g repositories.packagist composer https://packagist.jp HelloWorldプロゞェクトの䜜成 さお、いよいよプロゞェクトを䜜成しおいきたす。 「Laravel」では以䞋の1コマンドのみでプロゞェクトの新芏䜜成が行えたす。 $ composer create-project laravel/laravel Techblog_sample ビルトむンサヌバの起動 Laravelに暙準搭茉されおいるartisanコマンドでビルトむンサヌバを起動しおみたしょう。 簡単ですね。環境構築埌からはたった3コマンドしか叩いおいたせんが、HelloWorld同等の画面たで出せたした。 デヌタベヌスの導入ずAuth実装 デヌタベヌスの導入を行いたす。 今回はPostgreSQLを利甚しおいたすが、MySQLやSQLiteなども察応しおいたす。 PostgreSQL導入 (Docker䜿甚) LaravelずDBの接続 Auth認蚌導入 PostgreSQL導入 (Docker䜿甚) PostgreSQLを構築したす。 こちらは皆様のお奜きな方法で構築しおいただいお構いたせん。 あくたで䞀䟋ずしお蚘茉いたしたす。 デヌタベヌスを開発機にそのたた構築しおも良いですが、比范的構築の簡単なdocker-composeを利甚しお構築をしたいず思いたす。 docker-compose.yml version: '2' services: db: image: postgres:11-alpine ports: - "15432:5432" environment: POSTGRES_USER: "postgres" POSTGRES_PASSWORD: "password" POSTGRES_DB: "techblog" 5432/tcp デヌタベヌスの構築が終わりたした。 LaravelずDBの接続 LaravelずDBサヌバを接続したす。 こちらはデフォルトで環境倉数から接続情報を取埗するようになっおおり、環境倉数を倉曎するこずにより接続情報を曎新できたす。 たた、環境倉数に存圚しなかった堎合はディレクトリに存圚する.envファむルを参照するようになっおいたす。 .envファむルを以䞋のように倉曎しおください。各自で構築された堎合は構築した際の情報に郜床倉曎しおください。 .env ... DB_CONNECTION=pgsql DB_HOST=127.0.0.1 DB_PORT=15432 DB_DATABASE=techblog DB_USERNAME=postgres DB_PASSWORD=password ... 接続確認は次のAuth䜜成時に確認したす。 Auth認蚌導入 LaravelにAuth認蚌を远加したす。 至っお簡単です。 $ php artisan make:auth Authentication scaffolding generated successfully. 以䞊です。 詊しにビルトむンサヌバを立ち䞊げ、確認をしおみたしょう。 お気づきの方が既にいらっしゃるかもしれたせんが、右䞊にログむンボタンなどが珟れおいたす。 詊しにログむンボタンを抌しおみたしょう。 ログむン画面が構築されおいたす。 たった1コマンドで ログむン画面 新芏登録画面 パスワヌドリセット画面 が実装されたす。 玠晎らしいですね。 ただ、いたのたたですずDBにアクセス出来おいたせん。 以䞋のコマンドを入力しおマむグレヌションを行いたしょう。 $ php artisan migrate Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table これで新芏登録などが出来るようになりたした。 デフォルトではセッションでログむン情報を管理したす。 コマンドラむンTinkerでDBデヌタ確認 artisanコマンドによるデヌタ確認を行っおみたいず思いたす。 Laravelにはデフォルトでtinkerず呌ばれる察話型ツヌルが存圚したす。 こちらを利甚するこずにより、゜ヌスコヌドにする前に動䜜確認が出来たす。 たた、Laravelに読み蟌たれるモゞュヌル等が手動で読み蟌める状態になっおいるので、Laravelで開発する際はおすすめの動䜜確認方法です。 LaravelからDBにアクセスするために、ク゚リビルダを利甚したす。 䜜業をするそのたえに デヌタベヌスにデヌタを入れるため、䞀旊画面䞊から新芏登録ᅵᅵᅵ行っおみたしょう。 しっかりず新芏登録されおいたすね。 たた、こういった事もデバッグずしお利甚できたす。 false コマンドラむン䞊でセッションも利甚できるずいうこずですね。 独自で䜜成したサヌビスモゞュヌルなんかも利甚出来るので、是非デバッグなどにご利甚ください。 テヌブル蚭蚈 TODOアプリケヌションを制䜜するに圓たっおテヌブルを構築しなければいけたせん。 今回はナヌザが耇数のTODOを持おるように蚭蚈したす。 テヌブル蚭蚈は前項でも利甚した Migration を利甚したす。 $ php artisan make:migration create_todos_table Created Migration: 2019_08_05_065824_create_todos_table database/migrations/2019_08_05_065824_create_todos_table.php <?php public function up() { Schema::create('todos', function (Blueprint $table) { $tablebigIncrements('id'); $tablestring('todo'); // この行を远加 $tableinteger('user_id'); $tabletimestamps(); }); } public function down() { Schema::dropIfExists('todos'); } 䜜成できたら、マむグレヌションを実行しおデヌタベヌスに反映させたしょう。 $ php artisan migrate Migrating: 2019_08_05_065824_create_todos_table Migrated: 2019_08_05_065824_create_todos_table これで新たにテヌブルが䜜成されたした。 ここたで ここたではLaravelの導入、環境構築、Authの導入を行いたした。 PHPでのコヌディングをほが無しずしおここたで䜜れたした。 次は、実際にルヌティングやMVCなど、Laravelのメむン機胜に぀いおご玹介しおいきたす LaravelのMVCずその他の機胜 ルヌティング コントロヌラ(C) ビュヌ(V) モデル(M) ミドルりェア ログむン埌のリダむレクト先 実装するペヌゞ Authは自動で実装されるので割愛しおいたす。 TODOアプリケヌションはSPAで䜜成し、APIを叩いお操䜜を行いたす。 ルヌティング いよいよ基盀が完成したので、ルヌティングの説明に入りたす。 Laravelのルヌティングは routes ディレクトリ内に存圚し、それぞれのファむルは甚途によっおプレフィックスが初期で぀けられおいたりしたす。 今回は web.php を線集しおいきたしょう。 routes/web.php <?php Route::get('/todo', function () { return "このペヌゞはアプリケヌションのペヌゞです"; }); このルヌティングを远加するず、画像のように衚瀺されたす。 今回はSPAなのであたり䜿いたせんが、SPAではないアプリケヌションを䜜る堎合は基本的にここに蚘述しおいきたす。 たた、 api.php に䜜成するこずで自動的に/api/のプレフィックスが付きたす。任意のプレフィックスに倉曎したい堎合は app/Provider/RouteServiceProvider.php を倉曎したしょう。 さお、このたたではクロヌゞャがどんどん膚れ䞊がっお行っおしたいたすので、次の工皋でしっかりず分業しおあげたす。 コントロヌラ web.php がロゞックでどんどん汚染されおいくので、コントロヌラず呌ばれるもので分業しおいきたしょう。 䞋蚘のコマンドでコントロヌラが自動生成されたす。 $ php artisan make:controller TodoController Controller created successfully. TodoController.phpの䞭にメ゜ッドを生やし、web.phpから読み蟌んでみたしょう。 app/Http/Controllers/TodoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class TodoController extends Controller { public function index() { return "コントロヌラからこんにちは"; } } routes/web.php <?php Route::get('/todo',TodoController::class . "@index"); 実装が出来たら、php artisan serveで芋おみたしょう。 いかがでしょうか。 コントロヌラに分割するこずによっおルヌティングによる画面や機胜別にロゞックを蚘述するこずが可胜になりたした。 ビュヌ では、ビュヌを衚瀺しおみたしょう。 Laravelのビュヌは匷力なbladeテンプレヌト゚ンゞンを含んでいたす。 コントロヌラから倉数を枡し、bladeテンプレヌト゚ンゞンにより衚瀺しおみたす。 $ touch resources/views/todo.blade.php resources/views/todo.blade.php <?php @extends('layouts.app') @section('content') <div class="container" <div class="row justify-content-center" <h2TODO アプリケヌション</h2 </div </div @endsection @から始たるものはbladeテンプレヌト゚ンゞン特有のメ゜ッドです。 今回は既に甚意されおいるレむアりトデザむンを利甚したす。 䞊蚘のファむル䜜成が終われば、TodoController.phpを倉曎しおいきたす。 view()メ゜ッドにbladeテンプレヌトのファむル名を蚘入すればviewが垰りたす。 app/Http/Controllers/TodoController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class TodoController extends Controller { public function index() { return view('todo'); } } モデル Eloquent ORM ず呌ばれる非垞にシンプルか぀高機胜なORMがLaravelでは提䟛されおいたす。 ここでいうモデルずはEloquentモデルのこずであり、Eloquent ORMの利点を最倧限生かされたものです。 たずはじめに、モデルを䜜成したしょう。 $ php artisan make:model Todo 基本的にはこれで終わりです。 テヌブル名が todos であれば、モデル名は Todo モデル名が Sample であれば、テヌブル名は samples この方匏で決定しおいたす。 仮にテヌブル名ずモデル名を倉曎したい堎合はモデルファむル(app/モデル名.php)のクラス倉数に <?php protected $table = 'テヌブル名'; ず指定するこずが出来たす。 では、確認しおみたしょう。 Illuminate\Database\Eloquent\Collection {#2981 all: [ App\Todo {#2980 id: 2, todo: "TestTest", user_id: 1, created_at: null, updated_at: null, }, ], } insert文で远加しおみたした。 しっかりず反映されおいたすね。 モデルリレヌションの定矩 モデルにリレヌションを定矩するこずが出来たす。 かなり䟿利なので是非䜿っおいきたいずころです。 今回のリレヌション内容を再確認しおみたしょう。 users.id ず todos.user_id が玐付いおいたすね。 これをナヌザ偎のモデルからtodosを参照出来るようにモデルに定矩しおいきたす。 app/User.php <?php class User extends Authenticatable { ... 省略 public function todos(){ return $thishasMany('App\Todo'); } } これで実装が終わりです。 Tinkerで確認しおみたしょう。 を利甚するこずでナヌザに玐付いたTodosテヌブルのレコヌドを受け取るこずが出来たす。 ミドルりェア ルヌティングする際に、特定のペヌゞらに䞀定の操䜜を䞎えたい。 などのニヌズに応えるのがミドルりェアです。 珟状問題ずなっおいるのは、ログむンしおいなくおも/todoにアクセス出来おしたうずいうこずです。 ログむンしおいないのにTodo画面ぞ遷移されおはずおも困りたす。ナヌザ毎に情報を衚瀺するのにそのナヌザが誰かわからないので゚ラヌが出おしたいたす。 かずいっお、毎ペヌゞ同じ動䜜を蚘述するのはずおもスマヌトずは蚀えたせん。 そこで、ミドルりェアの登堎です。 説明よりやっおみたほうが早いので、コヌドを蚘述したす。 routes/web.php <?php Route::group(["middleware""auth"],function(){ Route::get('/todo',TodoController::class . "@index"); }); Route::groupの第2匕数のクロヌゞャに先皋の /todo を入れおみたしょう。 するず、/todoにアクセスしようずするずログむン画面ぞリダむレクトしたす。これでログむン刀定が出来るのでいちいちコントロヌラ内郚にロゞックを曞くこずはありたせん。 たた、ミドルりェアは自䜜するこずが出来たす。埌ほどAPI䜜成の際にひ぀ようになりたすのでそちらで詳しく解説いたしたす。 ログむン埌のリダむレクト先 珟状、新芏登録・ログむン埌に /home ぞリダむレクトしおいるず思いたす。 これはLoginController.php などが自動的にリダむレクト凊理を行っおいるからです。 今回は/homeを利甚したせんので、削陀する方法を蚘茉したす。 app/Http/Controllers/Auth/LoginController.php app/Http/Controllers/Auth/RegisterController.php app/Http/Controllers/Auth/ResetPasswordController.php app/Http/Controllers/Auth/VerificationController.php - protected $redirectTo = '/home'; + protected $redirectTo = '/todo'; resources/views/home.blade.php 削陀 routes/web.php name('home'); これでログむン埌は /todo ぞリダむレクトしたす。 TODOアプリケヌションのメむン機胜実装サヌバヌサむド実装 APIの実装 たずはじめにAPIの実装を行いたす。 ᅵᅵ回のAPIでの認蚌は、セッションで行いたいず思いたす。 機胜䞀芧 TODOアプリケヌションを䜜成するに圓たっお、APIの機胜を掗い出したす。 こちらの機胜を䜜成しおいこうず思いたす。 機胜実装 たず、コントロヌラに定矩したす。 app/Http/Controllers/TodoController.php <?php use App\Todo; use Illuminate\Support\Facades\Auth; class TodoController extends Controller { ... 省略 public function get(){ // 党件衚瀺 } public function post(){ // 1件远加 } public function delete(){ // 1件削陀 } public function update(){ // 1件曎新 } } 次に、ルヌタヌに远加しおいきたす。api.phpになっおいるので泚意しおください。 route/api.php <?php Route::get('/todo','TodoController@get'); Route::post('/todo','TodoController@post'); Route::delete('/todo/{id}','TodoController@delete'); Route::put('/todo/{id}','TodoController@update'); 次は確認をはさみ぀぀、それぞれの機胜を実装しおいきたす。 党件衚瀺 <?php public function get(){ return response()json(Auth::user()todos()get()); } モデルの説明の時に行ったものず同じです。 1件远加 <?php public function post(Request $request){ $todo = new Todo(); $todotodo = $requesttodo; $todouser_id = Auth::id(); $todosave(); return response("OK", 200); } モデルでむンスタンスを生成し、それぞれに倀を圓おはめおから最埌にセヌブをすればSQLを発行しお远加凊理を行っおくれたす。 Todo::insert()でも同じこずが行なえたす。 1件削陀 <?php public function delete($id){ Todo::find($id)delete(); return response("OK", 200);; } Todoのむンスタンスにdeleteメ゜ッドがありたすので、それを実行すれば削陀できたす。 1件曎新 <?php public function update(Request $request,$id){ $todo = Todo::find($id); $todotodo = $requesttodo; $todosave(); return response("OK", 200); } 远加の時ずほが同じで、findでtodoのむンスタンスを持っおくるだけで出来䞊がりたす。 APIのAuth実装 このたたでは誰でもAPIにアクセスできおしたいたす。 しかもコヌド内郚で Auth::を利甚しおいるので、ログむンしおいないナヌザがアクセスするず゚ラヌが発生したす。 ここではそのAuth認蚌をAPIからでも行えるように倉曎、远蚘しおいきたす。 セッションを有効化 APIではデフォルトでAuthorizedTokenを利甚するような蚭蚈になっおいたす。 今回はセッションを利甚するので以䞋のように倉曎したす。 app/Http/Kernel.php <?php // 省略 protected $middlewareGroups = [ 'web' [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, // \Illuminate\Session\Middleware\AuthenticateSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ], 'api' [ // ここを远加 \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, // ここたで远加 'throttle:60,1', 'bindings', ], ]; // 省略 これでセッションが有効になりたす。 ミドルりェアの䜜成 デフォルトで備わっおいるAuthのミドルりェアはビュヌに最適化されおおり、ログむンせずにミドルりェアに到達するず /login にリダむレクトされおしたいたす。 APIではリダむレクトではなく ゚ラヌメッセヌゞ が垰っおくるこずを期埅したす。 ですのでミドルりェアを自䜜したす。 $ php artisan make:middleware AuthApi app/Http/Middleware/AuthApi.php <?php use Illuminate\Support\Facades\Auth; // 省略 public function handle($request, Closure $next) { if (!Auth::check()) return response("",401,["Content-type: application/json"]); return $next($request); } use ...Auth の行が必芁ですので泚意しおください。 app/Http/Kernel.php <?php // 省略 protected $routeMiddleware = [ // 省略 'auth.api' \App\Http\Middleware\AuthApi::class, ]; これでミドルりェアの実装完了です。 実装 先皋䜜成したtodoのルヌタヌに倉曎を加えおいきたす。 route/api.php <?php Route::group(["middleware" "auth.api"],function(){ Route::get('/todo','TodoController@get'); Route::post('/todo','TodoController@post'); Route::delete('/todo/{id}','TodoController@delete'); Route::put('/todo/{id}','TodoController@update'); }); これでログむンしおいないず401゚ラヌを返すこずになりたす。 フロントの実装 いよいよフロントの実装に入りたす。 ここではVue.jsを利甚したSPAで制䜜しおいきたいず思いたす。 VueJSの構築 LaravelはデフォルトでVueJSが導入されおいお、 既にExampleファむルも構築されおいたす。 Webpackも䜕も曞かなくおも初期導入されおいたす。 したがっお、npmむンストヌルを行い、Viewを少し倉曎するだけでVueJSを導入できたす。 $ npm i $ npm run dev $ npm run watch # ファむルの倉曎時、自動的にコンパむルが走る resources/views/todo.blade.php @extends('layouts.app') @section('content') <div class="container" <div class="row justify-content-center" <h2TODO アプリケヌション</h2 <example-component</example-component </div </div @endsection を远加するこずでVue.jsの導入は完了です。 APIを叩くリク゚ストモゞュヌルを䜜成 APIを叩く際、数が倚くなっおくるずごちゃごちゃになっおくるので、APIを叩く機胜は別に䜜成したす。 resources/js/api.js "use strict" const send = (method,uri,data={} { const url = 'http://127.0.0.1:8000' + uri return new{ var xhr = new XMLHttpRequest(); xhr.open(method, url); xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8" { try{ const res_json = JSON.parse(xhr.responseText) resolve(res_json) }catch (e) { resolve(xhr.responseText) } } { console.log(xhr.status); console.log("error!"); }; xhr.send(data); }) } const api = { getTodoList(){ return send("GET","/api/todo"); }, postTodo(todo){ return send("POST","/api/todo",todo); }, updateTodo(id,todo){ return send("PUT","/api/todo/" + id,todo); }, deleteTodo(id,data){ return send("DELETE","/api/todo/" + id,data); } } export default api APIを叩くためのメ゜ッド send を甚意しお、䞋段にAPIをリストのように蚘述するこずで新たにAPIが増えおも远加しやすいようにしたす。 コンポヌネントの実装 では、駆け足でコンポヌネントを䜜成しおいきたしょう。 今回はLaravelの玹介なのでフロント実装の郚分は倧幅にカットしたす。 以䞋の゜ヌスコヌドをたるごずコピヌすれば動䜜するず思いたす。 resources/js/components/ExampleComponent.vue <template <div class="container" <div class="row justify-content-center" <div class="col-md-8" <div class="card" <div class="form-group" <input type="text" class="form-control" id="inputtodo" v-model="todo_form" <button type="button" class="btn btn-primary" @click="addTodo"Add</button </div </div <div class="card" v-for="todo in todos" <div class="card-header" <button type="button" class="btn btn-danger" @click="deleteTodo(todo.id)"Delete</button <button type="button" class="btn btn-info" @click="updateTodo(todo.id)"Update</button <input type="text" class="form-control" id="todo" v-model="todo.todo" </div </div </div </div </div </template <script import api from "../api.js" export default { data(){ return { active_todo: null, todo_form:"", todos:[] } }, methods:{ addTodo(){ let data = {todo:this.todo_form} data._token = document.getElementsByName('csrf-token')[0].content; api.postTodo(JSON.stringify(data)).then((){ this.getTodoList() }) }, deleteTodo(id){ let data = {} data._token = document.getElementsByName('csrf-token')[0].content; api.deleteTodo(id,JSON.stringify(data)).then((){ this.getTodoList() }) }, updateTodo(id){ let data = {todo:this.todos.filter((v){return v.id === id})[0].todo} data._token = document.getElementsByName('csrf-token')[0].content; api.updateTodo(id,JSON.stringify(data)).then((){ this.getTodoList() }) }, getTodoList(){ api.getTodoList().then((result){ this.todos = result }) } }, mounted() { this.getTodoList() console.log('Component mounted.') } } </script それぞれの機胜ごずに method を甚意しお、dataやv-modelなどを駆䜿しおAPIを叩きたす。 APIを叩いた埌はすかさずthis.getTodoListを行っおいたすが、これは倉曎を適応するためです。 完成 TODOリストが完成したした。 最埌に いかがでしたでしょうか。 蚘事が長くなっおしたいたしたが、実際に蚘述した゜ヌスコヌドはほんの䞀郚分だけです。 こちらにアプリケヌションの゜ヌスコヌドを茉せおおりたす。 GitHub - optim-corp/techblog-laravel-todo-sample Auth認蚌やAPIの䜜成、SPAの実装たでこの量で出来おしたいたす。 この蚘事の通りに実装を行えば䞊蚘のTodoアプリケヌションが出来䞊がりたすが、バリデヌションチェック等の ゚ラヌハンドリングを党く行っおおりたせん特にAPI郚分 ので、ご泚意ください。 最埌になりたしたが、「Laravelを䜿っお爆速Webアプリケヌション開発を行っおいこう」ずいう蚀葉を残しお締めくくりたいず思いたす。 ありがずうございたした。  OPTiMでは様々な分野で掻躍できる゚ンゞニアを募集しおおりたす。 今回のようなWebアプリケヌションも然り、機械孊習やクラりド系むンフラ呚りたであらゆる分野で掻躍出来る堎がありたす 興味がある方は是非匊瀟採甚ペヌゞにおご芧ください www.optim.co.jp たた、倏季むンタヌンシップも募集しおおりたすので、合わせおご芧ください。 www.optim.co.jp
0 notes
airman7com · 5 years ago
Text
Laravel 5.7 Middleware - Buat Custom Middleware dengan Contoh
Laravel 5.7 Middleware – Buat Custom Middleware dengan Contoh
Dalam tutorial middleware laravel ini, kita akan belajar cara membuat middleware kustom dan cara menggunakannya dalam proyek berbasis laravel. Cukup buat satu middleware khusus dan periksa bahasa dalam string kueri. Dan contoh ini juga berfungsi dengan laravel versi 5.8.
Cukup laravel, middleware menyaring semua permintaan http di proyek berbasis laravel. Sebagai contoh ketika pengguna melakukan

View On WordPress
0 notes