#laravel 5.8 named routes
Explore tagged Tumblr posts
laravelvuejs · 6 years ago
Text
Laravel 5.8 Tutorial From Scratch - e24 - URL Helpers - Laravel
Laravel 5.8 Tutorial From Scratch – e24 – URL Helpers – Laravel
Laravel 5.8 Tutorial From Scratch – e24 – URL Helpers – Laravel
[ad_1]
In this episode, we explore the 3 URL Helpers offered by Laravel out of the box and refactor our project to use them.
For the best experience, follow along in our interactive school at https://www.coderstape.com
Resources Course Source Code https://github.com/coderstape/laravel-58-from-scratch
Hit us up on Twitter with any

View On WordPress
0 notes
harrisongreeves-blog · 6 years ago
Text
Laravel 6.0: What You Should Know
Tumblr media
Since the inception of Laravel 5.0 around 4.5 years ago, the Laravel ecosystem has blossomed into something that leaves users nothing to complain about, to say the least. Laravel Nova, Laravel Horizon, Laravel Echo, Laravel Scout, and Laravel Passport are just some of the tools that have been introduced since then. At the time of this writing, we’re on Laravel 5.8 and Taylor Otwell has decided to skip past 5.9 on to 6.0 on the 3rd of September. Previously, Taylor has stressed that this won’t be a major paradigm shift for Laravel and the most significant change will be the transition to semantic versioning. However, this doesn’t mean that there aren’t plenty of new features worth talking about.
Let’s dive into some of the smaller changes first.
The Smaller Things
Authorization
Tumblr media
Authorization messages can now be made easier for users to understand. Before Laravel 6.0, the infrastructure wasn’t in place to easily give a specific response to a user when they were given an authorization-related error. The status code could be given fairly easily, but giving a custom error message was more complicated back then. Giving a custom messaged required the developer to create a new file and write their own exceptions.
Now, to get a customizable authorization response, you can simply use the Gate::inspect method when linking to the function that enables you to receive the response. Delivery of the message to the front-end is also easy to organize. Simply add $this->authorize or Gate::authorize to a suitable route or controller.
No More Default Front-End
Tumblr media
The typical front-end setup you are given when you first start a Laravel project is now gone. This means the Vue and Bootstrap code you would usually see, would have now been removed. What it’s been replaced with is unknown. Perhaps, it hasn’t been replaced. Strangely, the make:auth command, used to provide the login system scaffolding is now not a part of the original Laravel install either. To be honest, the rationale behind this change is unclear to me. However, given Laravel’s versioning adjustment, it makes sense that third-party technologies like Vue and Bootstrap that haven’t recently undergone the same changes could cause conflict. Though, this is merely speculation.
If you want access to the old UI, you can extract a composer package that contains it with the CLI: composer require laravel/ui and php artisan ui vue --auth.
Lazy Collections
Tumblr media
This is one of the more interesting additions. If you’re new to Laravel, Collections are tools that make it easier for you to manipulate arrays. Eloquent, one of the two main tools in Laravel used to communicate with databases, returns its queries as Collection instances. Check out the docs for Collections if you think you’re gonna lack context in a moment. https://laravel.com/docs/5.8/collections
So, what are Lazy Collections? Traditional Collections are often used for working with large amounts of data. When they run into data-heavy files, they’ll try and store all of that data at once. This may sound quick and convenient but the downside is that this is very memory-taxing. Lazy Collections solve this problem by only storing the part of the file they need, and thus, save memory usage and boost performance.
If you understand how lazy loading works then you’ll be familiar with my previous explanation. Lazy loading works the same way. When you make a request to the server with lazy loading implemented, the browser will only return the part of the web page it knows you’re going to use immediately. Then, when the user scrolls down the page or clicks on an internal link, the server will provide you the necessary content it knows you need. This way, only memory that is needed at that particular moment is being used. This method increases speed. Lazy Collections is kind of like lazy loading but with arrays from a database and not content on a webpage.
The Bigger Things
Laravel Ignition
Tumblr media
So yeah, the new error page for Laravel is called Ignition and it looks awesome. It’ll be the default error page for Laravel when 6.0 releases. However, if you don’t feel like making the switch to 6.0 just yet, that’s fine, you can still install Ignition on previous versions. Let’s talk about what Ignition brings to the table.
With Whoops (the current default Laravel error page), stack traces and relevant code snippets are shown in an error page, but this doesn’t always lead the developer to the solution. Worse, sometimes the stack traces just reference compiled paths. This can it make it difficult to find the necessary non-compiled files to fix because they aren’t listed anywhere on the error page. Thankfully, this isn’t a problem with Ignition, it can display to you the non-compiled file where the problem actually exists. By clicking on a pencil icon, you can go directly to the file in your chosen editor.
The second coolest feature of Ignition is that it can display potential solutions when displaying an error message. Most error pages just leave you with the error. For example, if the error is that you misspelled a property name, Ignition will tell you that the property has been misspelled and offer you the correct spelling. Solution suggestions can be way more sophisticated than this, I’ll link you to the source down below. Your suggestions are even customizable!
You wanna know the coolest feature? These solution suggestions are actually runnable!
Tumblr media
Yes, really. Take a look at this short demo by one of the creators, Freek Van der Herten.
https://youtu.be/EZu0-CwTU9Q
Also, you can add your own runnable solutions too! This is great as Ignition is open source so people in the Laravel community will undoubtedly contribute their own solutions for everyone to use.
There’s a bunch of other cool features too such as creating your own tabs (yes Ignition has tabs) and sharing your error messages with other people. This is done using Flare, a tool that comes with Ignition.
For everything about Laravel Ignition and Flare, visit https://freek.dev/1441-ignition-a-new-error-page-for-laravel.
Laravel Vapor
Tumblr media
Another big one. Laravel Vapor is a serverless deployment platform for Laravel. But wait, why do we need a deployment platform? We already have Laravel Forge, right? As beloved as Forge is amongst the Laravel community, it does have its limitations. It doesn’t have autoscaling to deal with large sudden increases in traffic that prevent your site from crashing. Also, configuration is required when OS or PHP updates occur. Vapor has autoscaling, so, you don’t have to worry about sudden spikes in your traffic causing website downtime. In addition, because of the serverless structure of Vapor, it also handles all the updates you may stress about when using Forge.
Vapor’s website is very clean looking and everything seems easy to find. When you deploy a project, you can see the different stages of the deployment process loading on the UI. I find this to be very reassuring and comforting. You can also rollback your application with a click of a button. Just click on “rollback” and it’ll do just that. Pretty neat. Same deal if you want your app to undergo maintenance. Just click on the “maintenance mode” button.
Another cool feature of Laravel Vapor is that you’re able to set alarms. What do I mean by that? For example, to know when your website traffic suddenly blows up, you can set a certain amount of HTTP requests per minute, and if your website hits that limit, the alarm will go off, informing you of the surge in traffic. Taylor Otwell showcases this and other conditionals in his Laravel Vapor demo which I’ll link to below.
There’s so much to cover with Laravel Vapor and the Laravel update itself. Because of this, I didn’t really want to dive into the complexities too much in this post. To learn more about the technical aspects of Laravel 6.0, you can take a look at the release notes here https://laravel.com/docs/6.0/releases. For more info on Laravel Vapor, visit this video by Taylor Otwell https://www.youtube.com/watch?v=XsPeWjKAUt0&t=362s.
1 note · View note
decodewebin · 6 years ago
Link
Here is another interesting topic of guard in laravel we are going to cover in this post. As we all know user authentication can be achieved in jiffy, that is, run php artisan make:auth and you will get controllers, blade views all ready to launch with authentication.
But..but.. Here is the catch. Laravel provides default authentication on User model or users table, what if there are two types of users completely different to each other, for example application users and admins ?
One thing we can do is, make a column in users table with name as type and there we define type of user, 1 for admin and 0 for normal user. This method is completely wrong, do not do this ever. Period.
Keep normal users in user table and for admins create another table as admin. Laravel ships a default authentication guard called as web which is applied on User model. For instance go to config/auth.php
'defaults' => [        'guard' => 'web',        'passwords' => 'users',    ],
Table of Contents
What is a guard in laravel authentication?
Create middlewares for normal users and admin users routes
Register middlewares in Kernel.php
Apply middlewares on their respective routes in web.php
Conclusion
How to create a guard a in laravel ?
What is middleware in laravel ?
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
laravelvuejs · 6 years ago
Text
𝐋𝐀𝐑𝐀𝐕𝐄𝐋 6 ROLES and PERMISSIONS + ADMIN AREA - EASY LARAVEL TUTORIAL - Part 1 - Laravel
𝐋𝐀𝐑𝐀𝐕𝐄𝐋 6 ROLES and PERMISSIONS + ADMIN AREA – EASY LARAVEL TUTORIAL – Part 1 – Laravel
𝐋𝐀𝐑𝐀𝐕𝐄𝐋 6 ROLES and PERMISSIONS + ADMIN AREA – EASY LARAVEL TUTORIAL – Part 1 – Laravel
[ad_1]
Laravel 5.8 / Laravel 6 Roles & Permissions tutorial.
Create roles, permissions and an admin area in Laravel with this easy tutorial.
– Create Role models which define what name the role has – Create middleware to protect certain routes from being accessed – Add checks to controller methods to prevent

View On WordPress
0 notes