#laravel 5.8 insert
Explore tagged Tumblr posts
laravelvuejs · 5 years ago
Photo
Tumblr media
Laravel 5.8 Ajax Crud Tutorial – Insert or Add Data Learn How to insert or Add data into MySQL database in Laravel 5.8 using Ajax and Bootstrap modal with file upload.
0 notes
laravelnews4u · 6 years ago
Photo
Tumblr media
Learn how to get Last Inserted ID with Laravel 5.8 https://t.co/nh7YyF6eSk #laravel #php #dev #css3 #html5 #js #coder #code #geek #angularjs #coding #developer #bootstrap #lumen #js #Programming #jquery #ajax #javascript https://t.co/tb7LHVnwVW
5 notes · View notes
concettolabs · 6 years ago
Text
Laravel 5.8.33: Let’s Talk About All New Email Validation Rule Options In It
Tumblr media
The team of Laravel has released all-new v5.8.33 in the month of August. These new versions have new capabilities added to the email validation rule that include the latest changes and some of the fixes.
Let’s have a look at the changes :
From requests a user can now provide a passedValidation() callback that will fire once the validation has passed:
public function passedValidation()
{       $this->replace(['name' => 'Adam']);}
These passedValidation callbacks can be helpful for applying filters to data without intrusive with validation.
The new type of email validation support has been implemented by Dries Vints using the egulias/EmailValidator package.
When checking for valid emails, the improved email validation rule acquaints the ability to add multiple email validators.
Example:
$request->validate([
   'email' => 'email:rfc,dns'
]);
By referring to the latest
laravel validation
documentation for 5.8 you can get to know about the new parameters possible in the email validation rule. The possible rules include strict, spoof, dns, and rfc filter.
Another support added by Dries Vints is for Redis 5.0 in a backward-compatible way so that all can support v5.0 in starting in this release.
For MySQL and Postgres ‘insert ignore’ support was added and to learn it in detail you need to check out add insert ignore support on GitHub.
Ignore works during an insert that means if the database runs into errors, it generally terminates and doesn’t insert any rows. While with ignore, the database will ignore invalid data and insert valid rows.
The amazing last feature that is added is the ability to use the custom, Whoops Handler. For more details, you can check on GitHub.
Have A Look On Whole Difference Between 5.8.32 and 5.8.33 as per on GitHub:
v5.8.33 :
Added
Implement new types for email validation support
Added ValidatesWhenResolvedTrait::passedValidation() callback
Allowed to override the existing Whoops handler
Added Redis 5 support
Added insert or ignore support
Fixed
Avoid undefined index errors when using AWS IAM
Fixed exception message in the ProviderRepository::writeManifest()
Fixed command testing of output and questions expectations
Added ignoring of classes which are not instantiable during event discovery
Fixed non-displayable boolean values invalidation messages
Used real class name for seeders in the output
Fixed invalid link expiry count in ResetPassword
Refactoring
Simplified isset()
Why To Wait?
Tumblr media
Get in touch with Concetto Lab to get the best applications and reshape your business today. We provide apps that are elevated in performance and quality with laravel application development in minimal cost. Our laravel development services includes laravel customization and integration, website migration using laravel, laravel framework development, and laravel support & maintenance.
0 notes
rafi1228 · 6 years ago
Link
Learn to master Laravel to make advanced applications like the real CMS app we build on this course
What you’ll learn
Learn to build applications using laravel
To install Laravel using Windows and MAC
You will learn how use Laravel
You will learn how to use routes
You will learn how to create and use Controllers and what they are
You will learn how to create Views an what they are
You will learn to use the templating engine Blade
How to connect and use Databases
How to create migrations and what they are
You will learn about Laravel ORM (Object Relational Mapper) and Raw SQL queries. Database stuff 🙂
How to use Laravel Tinker – Command line program to play around with Laravel without persisting data
Database: Eloquent One to One – CRUD
Database: Eloquent One to Many – CRUD
Database: Eloquent Many to Many – CRUD
Database: Eloquent Polymorphic – CRUD
Form Validation
You will learn to download third party libraries to add to Laravel
You will learn to upload files
You will learn about Middleware and security
You will learn about sesssions
You will learn about sending emails
You will learn Github or version control
You will learn how to install a WYSIWYG editor
To install a commenting system / Disqus
You will learn to create a BULK functionality that you can use the CRUD on it
You will learn to deploy Laravel on share hosting accounts, like godaddy
And lots of more cool things
Requirements
Basic OOP PHP
Description
VERSION 5.2 but we keep updating as new version come out. This is an evergreen course because we keep adding new fresh content all the time!
UPDATES …….
5.3 – section 33
5.4 – section 38
5.5 – section 40
5.6 – section 41
5.7 – section 43
5.8 – section 43
We will keep updating the project as new versions come out!
Over 23,000 students in this course and over 380,000 students here at Udemy.
Best Rated, Best Selling, Biggest and just baddest course on Laravel around 🙂
Oh it’s also the best course for complete beginners and of course regular beginners 🙂
Laravel has become on of the most popular if not the most popular PHP framework. Employers are asking for this skill for all web programming jobs and in this course we have put together all of them, to give you the best chance of landing that job; or taking it to the next level.
Why is Laravel so popular? Because once you learn it, creating complex applications are easy to do, because thousands of other people have created code we can plug (packages) in to our Laravel application to make it even better.
There are many reasons why Laravel is on the top when it comes to php frameworks but we are not here to talk about that, right?
You are here because you want to learn Laravel, and find out what course to take, right? Alright lets lists what this course has to offer, so that you can make your decision?
Benefits of taking this course (I promise to be  brief)
1. Top PHP instructor (with other successful PHP courses with great reviews)
2. Top support groups
3. An amazing project that we will be building and taking to Github
4. Lots of cybernetic coffee to keep you awake…..
5. Did I mention I was not boring and you will not fall asleep?
Ok, Let’s break each of these down, shall we?
Top Instructor…..
I don’t like boasting but my other PHP courses can speak for me 🙂
Top support groups
I make sure everybody helps in the class and we also have Facebook support groups if needed.
The Amazing project / real life application….
On this project you will learn everything you need for creating awesome applications the easy way with Laravel, and new features will be implemented all the time, just the the curriculum and look at the updates section.
Full Source Code is Available at Github 
Oh yeah, we take this to Github (A app repository online) and even show you how, so you will learn that too.
—————————————-
Practicality…………………..
Lots practical skill with some theory so you get more experience that its essential for becoming a Professional Laravel Developer.
This course will take your game a new level. Imagine being able to create the next Facebook or twitter, or even getting the developer job you dream of? What about just a programming job? You can achieve all that if you study with us and really focus. We will help you along the way.
Here are some my lovely students (Not to show off of course) 🙂 
REVIEWS  ——————————->
Rating: 5.0 out of 5
*****
Understood MVC in one sentence after so many years! Great job Edwin. A great deal of effort has been put by Edwin to create the content in two parts , first for understanding the basic components (eloquent relationships, views, controller etc) and then actually using it in a project. And he loves teaching. We love learning from him!
———————————————————
Rating: 5.0 out of 5
Great Course! Everything was explained well and if you will have any questions they will give you good answers, or you will find the answers in Q&A.
———————————————————
Rating: 5.0 out of 5
I would recommend this course to Laravel beginners like me, it covers a lot and the idea of learning on short-manageable videos + learning from errors that follow is a home run best approach! I am satisfied with course and especially with teacher Edwin who is extreme motivator…….
Rating: 5.0 out of 5
I loved the course!! Learned a lot and actually applied it, I’m very happy. 10-stars!!!
———————————————————
Get it? Not every course its perfect we do get the best reviews for a good reason, of course you can’t please everybody but we try.
Are you ready to to create the next Facebook or Twitter? …………….
Lets start with the fundamentals 
Downloading Laravel
Installing it with composer
Lets also use Laravel Homestead
We learn about Routes, Controllers, views, models, migrations, template engines, middleware and more
Lets learn the CRUD, create, read, update and deleting data 🙂
Wait, lets also learn the CRUD with all the ELOQUENT relationships,
Lets learn so database stuff 🙂
One To One
One To Many
One To Many (Inverse)
Many To Many
Has Many Through
Polymorphic Relations
Many To Many Polymorphic Relations
Querying Relations
Relationship Methods Vs. Dynamic Properties
Querying Relationship Existence
Querying Relationship Absence
Counting Related Models
Inserting & Updating Related Models
The save Method
The create Method
Belongs To Relationships
Many To Many Relationships
Let me break down some things from the projects but not all, cause my hands are a little tired 🙂
Authentication system
Multi users with roles, Admins, subscribers and whatever you want 🙂
User profiles
Uploading photos, multi pictures
Multiple input selections
User, CRUD
Pos CRUD
Category CRUD
Photo CRUD
Pretty URL’s
Commenting system, reply system with tree
Disqus commenting system
Sessions, and flash messages
Email Sending
EMAIL testing
Restrictions
Deployment
Lots more, too many to list
Oh did I mention we keep updating the course with new versions? 
Did I also mention this LARAVEL course is the best rated course, the best selling and the biggest of its kind here in Udemy?
Lets start this and let’s create big things 🙂
Who this course is for:
People looking for web programming jobs should take this course
People looking to learn everything about laravel should take this course
Students who want to take their PHP skills to another level should take this course
Created by Edwin Diaz, Coding Faculty Solutions Last updated 3/2019 English English
Size: 9.60 GB
   Download Now
https://ift.tt/1sLScUT.
The post PHP with Laravel for beginners – Become a Master in Laravel appeared first on Free Course Lab.
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アプリケーションを制作するに当たってテーブルを構築しなければいけません。 今回は1ユーザが複数の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
Laravel 5.8 Crud Tutorial with Upload File - 1 - Laravel
Laravel 5.8 Crud Tutorial with Upload File – 1 – Laravel
Laravel 5.8 Crud Tutorial with Upload File – 1 – Laravel
[ad_1]
Learn from Scratch Laravel 5.8 CRUD(Create, Read, Update, Delete) operation with File upload. In this part you can find how to download Laravel 5.8, how to make database connection in Laravel 5.8, how to migrate table from Laravel 5.8, how to make model in Laravel 5.8 and How to create controller in Laravel 5.8. This all feature we…
View On WordPress
0 notes
laravelvuejs · 6 years ago
Text
Laravel 5.8 Ajax Crud Tutorial - Insert or Add Data - Laravel
Laravel 5.8 Ajax Crud Tutorial – Insert or Add Data – Laravel
Laravel 5.8 Ajax Crud Tutorial – Insert or Add Data – Laravel
[ad_1]
Learn How to insert or Add data into MySQL database in Laravel 5.8 using Ajax and Bootstrap modal with file upload. How to Insert Data in MySQL table using Ajax in Laravel 5.8. How to insert data in Laravel 5.8 using model. How to insert data in Laravel 5.8 using Ajax. How to make Ajax Crud Application in Laravel 5.8 framework.
View On WordPress
0 notes