20210513のlaravelに関する記事は11件です。

Docker X Laravel PHP CS Fixer を導入して、ソースコードを自動整形する

環境 https://github.com/ucan-lab/docker-laravel 最強のLaravel開発環境をDockerを使って構築する 記事執筆時バージョン PHP: 8.0 Laravel: 8.0 php-cs-fixer: 3.0.0 PHP Coding Standards Fixer(php-cs-fixer) リポジトリ名はPHP-CS-Fixer、正式名称はPHP Coding Standards Fixer、コマンド名はphp-cs-fixerとなります。 php-cs-fixer の導入 $ composer require --dev bamarni/composer-bin-plugin $ composer bin tools require friendsofphp/php-cs-fixer .php-cs-fixer.dist.php php-cs-fixerの設定ファイルを追加します。 $ touch .php-cs-fixer.dist.php .php-cs-fixer.dist.php <?php declare(strict_types=1); $finder = PhpCsFixer\Finder::create() ->in([ __DIR__ . '/app', __DIR__ . '/config', __DIR__ . '/database/factories', __DIR__ . '/database/seeders', __DIR__ . '/routes', ]); $config = new PhpCsFixer\Config(); return $config ->setRiskyAllowed(true) ->setRules([ '@PhpCsFixer:risky' => true, 'blank_line_after_opening_tag' => false, 'linebreak_after_opening_tag' => false, 'declare_strict_types' => true, 'phpdoc_types_order' => [ 'null_adjustment' => 'always_last', 'sort_algorithm' => 'none', ], 'no_superfluous_phpdoc_tags' => false, 'global_namespace_import' => [ 'import_classes' => true, 'import_constants' => true, 'import_functions' => true, ], 'php_unit_test_case_static_method_calls' => [ 'call_type' => 'this' ], 'phpdoc_align' => [ 'align' => 'left', ], 'not_operator_with_successor_space' => true, ]) ->setFinder($finder); .gitignore に追加 vendor-bin ディレクトリと .php-cs-fixer.cache ファイルはGit管理は不要なので、 .gitignore に追加します。 /vendor-bin .php-cs-fixer.cache php-cs-fixer 実行 # version $ ./vendor/bin/php-cs-fixer --version PHP CS Fixer 3.0.0 Constitution by Fabien Potencier and Dariusz Ruminski # dry run $ ./vendor/bin/php-cs-fixer fix -v --diff --dry-run # fix $ ./vendor/bin/php-cs-fixer fix -v --diff GitHub Actions でプルリク作成時に自動チェックする $ mkdir -p .github/workflows $ touch .github/workflows/pull-request-php-cs-fixer.yml pull-request-php-cs-fixer.yml name: PHP Coding Standards Fixer on: pull_request: jobs: php-cs-fixer: runs-on: ubuntu-latest defaults: run: working-directory: backend steps: - uses: actions/checkout@v2 - name: Setup PHP uses: shivammathur/setup-php@v2 with: php-version: '8.0' - name: Prepare run: | wget https://github.com/FriendsOfPHP/PHP-CS-Fixer/releases/download/v3.0.0/php-cs-fixer.phar -O php-cs-fixer chmod a+x php-cs-fixer - name: OS Version run: cat /etc/os-release - name: PHP Version run: php -v - name: PHP CS Fixer Version run: php php-cs-fixer --version - name: PHP CS Fixer Run run: php php-cs-fixer fix --diff -vvv --dry-run 補足: ルールセット GitHubにルールセットがまとめられています。 おすすめルールセットは PhpCsFixer:risky です。 https://github.com/FriendsOfPHP/PHP-CS-Fixer/tree/3.0/doc/ruleSets 補足: php-cs-fixerの細かい設定 PHP-CS-Fixer Configuratorという便利なサービスがあります。 細かい変更を行いたい場合はこちらをご利用下さい。 https://mlocati.github.io/php-cs-fixer-configurator
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[簡単]モダン構成なSPAで作るチュートリアル⑥(編集・削除機能)

SPAで作るタスク管理アプリのチュートリアル - 編集・削除機能 今回は第④弾でReactで一覧テーブル作成する部分をやっていくで ①環境構築(Docker/Laravel/React.js/Material-UI) ②React側でルーティング設定 ③API取得してReactで一覧テーブル作成 ④API取得してReactで一覧表示 ⑤新規登録機能 ⑥編集・削除機能 今回は編集機能と削除機能をやっていくで 編集機能 こんな感じで一覧の編集ボタンを押すと該当のするタスクの編集が行える画面に遷移できるようにするで バックエンド側の実装 シンプルなCRUDだからバックエンドはそんなにややこしくないな。 ルーティングは下記のように記載 api.php Route::group(['middleware' => 'api'], function(){ Route::get('posts', 'App\Http\Controllers\Api\PostController@index'); Route::post('post/create', 'App\Http\Controllers\Api\PostController@create'); Route::post('edit', 'App\Http\Controllers\Api\PostController@edit'); //追記 Route::post('update', 'App\Http\Controllers\Api\PostController@update'); //追記 }); コントローラー PostController.php   // 編集画面に遷移するためのアクション public function edit(Request $request) { $post = Post::find($request->id); return $post; } //データを更新するためのアクション public function update(Request $request) { $post = Post::find($request->id); $post->name = $request->name; $post->content = $request->content; $post->save(); $posts = Post::all(); return $posts; } バックエンドはここまで 編集画面用のコンポーネント作成 入力フォームを新規作成機能を作った際のコンポーネントを再利用する /pages/PostEdit.jsを下記のように作成 PostEdit.js import React, { useState, useEffect } from 'react'; import { Card } from '@material-ui/core'; import { makeStyles, createStyles } from '@material-ui/core/styles'; import PostFrom from '../components/PostFrom'; const useStyles = makeStyles((theme) => createStyles({ card: { margin: theme.spacing(5), padding: theme.spacing(3), }, })); function PostEdit(props) { const classes = useStyles(); const params = props.match.params; const [editData, setEditData] = useState({name:'', content:''}); useEffect(() => { getEditData(); }, []) function getEditData(){ axios .post('/api/edit', { id: params.id }) .then(res => { setEditData(res.data); }) .catch(() => { console.log('通信に失敗しました'); }); } function updatePost(){ if(editData == ''){ return; } //入力値を投げる axios .post('/api/update', { id: params.id, name: editData.name, content: editData.content }) .then((res) => { setEditData(res.data); }) .catch(error => { console.log(error); }); } function inputChange(e){ const key = e.target.name; const value = e.target.value; editData[key] = value; let data = Object.assign({}, editData); setEditData(data); } return ( <div className="container"> <div className="row justify-content-center"> <div className="col-md-8"> <div className="card"> <h1>タスク編集</h1> <Card className={classes.card}> <PostFrom data={editData} inputChange={inputChange} btnFunc={updatePost} /> </Card> </div> </div> </div> </div> ); } export default PostEdit; ルーティングに記載 route.js import PostEdit from './pages/PostEdit'; //追記 function App() { return ( <div> <Switch> <Route path='/example' exact component={Example} /> <Route path='/' exact component={Home} /> <Route path='/post/edit/:id' exact component={PostEdit} /> //追記 Homeの一覧画面で編集ボタンをクリックすると対象のidを使ってリクエスト投げるように設定 Home.js //rows.pushの中の編集ボタンに keyとhrefを追加の編集ボタン rows.push({ name: post.name, content: post.content, editBtn: <Button color="secondary" variant="contained" key={post.id} href={`/post/edit/${post.id}`}>編集</Button>, //追加 deleteBtn: <Button color="primary" variant="contained">完了</Button>, }) 編集ボタンをクリックすると、対象のデータの編集画面に遷移できればOKや そのままデータを変更できることも確認しておくで 確認出来たらコミットしておこう # git add . # git commit -m "投稿編集機能の実装" 削除機能 完了を押したらデータが削除されるようにするで バックエンド ルーティング api.php Route::group(['middleware' => 'api'], function(){ Route::get('posts', 'App\Http\Controllers\Api\PostController@index'); Route::post('post/create', 'App\Http\Controllers\Api\PostController@create'); Route::post('edit', 'App\Http\Controllers\Api\PostController@edit'); Route::post('update', 'App\Http\Controllers\Api\PostController@update'); Route::post('delete', 'App\Http\Controllers\Api\PostController@delete'); }); //追記 コントローラー PostController.php public function delete(Request $request) { $post = Post::find($request->id); $post->delete(); $posts = Post::all(); return $posts; } apiを叩くdeletePostの定義 Home.js // createPostの下に記載 const deletePost = async (post) => { await axios .post('/api/delete', { id: post.id }) .then((res) => { this.setState({ posts: res.posts }); }) .catch(error => { console.log(error); }); } 完了ボタンのOnClickを追記 Home.js rows.push({ name: post.name, content: post.content, editBtn: <Button color="secondary" variant="contained" key={post.id} href={`/post/edit/${post.id}`}>編集</Button>, deleteBtn: <Button color="primary" variant="contained" href="/" onClick={() => deletePost(post)}>完了</Button>,//追記 }) ビルド $ make npm-dev 一覧表で完了ボタンを押し、対象のデータが削除されることを確認 コミットしておく $ git add . $ git commit -m "削除機能の実装" 完了
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Laravel】Seederファイルを作成して、ダミーデータを格納する

Seederファイルの作成が初見だったためメモです ファイルの作成 $ php artisan make:seeder 任意のファイル名 作成したファイルに以下のように記述しました。色んなパターンあると思います <?php use App\Models\Company; class CreateCompanySeeder extends Seeder { public function run() { $menu = Company::create([ 'name' => 'hoge-company' ]); } } 作成したファイルを実行するように記述する  /database/seeds/DatabaseSeeder <?php use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $this->call(CreateCompanySeeder::class); } } 実行 $ php artisan db:seed クラスを指定しても実行できる $ php artisan db:seed --class=CreateCompanySeeder
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelレイアウト

Laravelレイアウト 共通したデザインのページを使える様になる @yield(名前) : @sectionの内容をはめ込んで表示させる機能がある まずベースとなるテンプレートを作る viewにlayoutフォルダを作成、その中にファイル作成 view/layouts/helloapp.blade.php {{-- ベースとなるレイアウト用のテンプレート --}} <html> <head> {{-- @yield配置場所を示す場所なのでendセクションはない --}} <title>@yield('title')</title> <style> body {font-size:16px; color:pink; margin:5px;} </style> </head> <body> <h1>@yield('title')</h1> @section('menubar') <h2 class="menutitle">メニュー</h2> <ul> <li>@show</li> </ul> <hr size="1"> {{-- この部分にコンテントが読み込まれる --}} <div class="content"> @yield('content') </div> {{-- この部分にfooter読み込まれる --}} <div class="footer"> @yield('footer') </div> </body> </html> @sectionは2種類の書き方がある view/index {{-- extendで継承する ベースレイアウトにそって内容を入れていく --}} @extends('layouts.helloapp') <!-- sectionは2種類書き方がある --> <!-- ① セクション名、 設定するテキスト値--> @section('title', 'INDEX') {{-- ② endセクションで囲う --}} @section('menubar') {{-- 親(継承)の表示を指示できる --}} @parent インデックスページ @endsection ブラウザで見ると下記の様な表示になる 'view/layouts/helloapp.blade.php'を継承した'view/index'のページ <h1>INDEX</h1> <h2>メニュー</h2> <ul> <li>インデックスページ</li> </ul> @components 一部を切り離して作成、組み込みたい時に 下記が部品の様な役割 view/components/message <div class="message"> <p class="msg_title">{{$msg_title}}</p> <p class="msg_content">{{$msg_content}}</p> </div> view/index {{-- どのテンプレートか指定している'view/components/message' --}} @component('components.message') {{-- スロットは{{}}で指定された変数に値を設定できる --}} @slot('msg_title') これはメッセージ @endslot @slot('msg_content') これもメッセージ @endslot @endcomponent <p>これはメッセージ</p> <p>これもメッセージ</p> includeサブビュー componentsと似ているが単純にテンプレートを表示させるのみの場合有効 @slotなどはサブビューで利用できない @include(テンプレート名, [値の指定]) view/index @include('components.message', ['msg_title'=>'OK', 'msg_content'=>'NOT OK']) <p>OK</p> <p>NOT OK</p>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Cannot declare class (クラス名), because the name is already in useの対策

(ファイル名) % php artisan migrate を行うと Cannot declare class AddGoogleIdColumn, because the name is already in use というエラーが出ました。この内容としては、「そのクラス名宣言できませんよ。既に使われていますよ」とのことでした。 しかし、クラス名で検索しても他に重複は見つかリませんでした。調べてみるとnamespaceを変えると解決しましたという記事も見かけました。 namespaceとは namespaceとは、PHPで名前空間(エイリアス)を設定するために使用されるものです。 一般的にPHPフォルダーのはじめにnamespace <ファイルのパス>と記載します。 エイリアスをファイルのパスにすることで自動読み込みを行うことができるようにしています。 解決策 ファイル名でした!そのため以前のファイル名に復元させるとエラーは治りました!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Laravel8 laravel/ui】既存のusersテーブルからお好みのテーブルに変更する方法を分かりやすく素早く解説してみた

①usersモデルの複製 マイグレーションで作成しても大丈夫ですが、こっちの方が簡単だと思うので簡単な方を説明します。Custom.phpは適当に付けた名称なので、ファイル名は好きに決めてもらって大丈夫です。 パス:~/app/Models/ cp User.php Custom.php ②Custom.phpの編集 クラス名を変更するだけです class User extends Authenticatable ↓ class Custom extends Authenticatable ③~/config/auth.phpの編集 providers => users内のUser::classを先程作成したファイル名と同じくCustom::classに変更して下さい。 /* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\User::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], /* ↓ /* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */ 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Models\Custom::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], /* ④~/app/Http/Controllers/Auth/RegisterController.phpの編集 use App\Models\User; ↓ ①で複製したファイルの名前に変更してください use App\Models\Custom; protected function create(array $data) { //ここを変更する return User::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); } ↓ protected function create(array $data) { //ここを変更する return Custom::create([ 'name' => $data['name'], 'email' => $data['email'], 'password' => Hash::make($data['password']), ]); } protected function validator(array $data) { return Validator::make($data, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:users'], //←を変更する 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); } ↓ protected function validator(array $data) { return Validator::make($data, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'string', 'email', 'max:255', 'unique:テーブル名'], //←を変更する 'password' => ['required', 'string', 'min:8', 'confirmed'], ]); } ⑤ 終わりです 素早く且つ分かりやすく解説出来たでしょうか...
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

自分が書いたQiita記事まとめ

はじめに 私はプログラミング歴1年の初心者です。 実務でWebサイトのコーディングを1年間行ってきました。 そろそろシステム開発もできるようになりたいということで LaravelやReactをこれから勉強していこうと思っております。 この記事の目的 この記事をエントリーポイントにしようと思います。 自分が書いた記事をまとめておく記事です。 目次 HTML/CSS関係(初心者) Ruby関係(初心者) PHP関係(1年目以降〜) Python関係(1年目以降〜) JavaScript関係(1年目以降〜) リンク集 HTML/CSS関係(初心者) Ruby関係(初心者) Railsアプリ作成の記事(プログラミング学習を始めてから1ヶ月くらい?) PHP関係(1年目以降〜) Laravelの記事(就職後に勉強し始めたのである程度わかってきたくらい?) Python関係(1年目以降〜) Pythonの記事 Djangoの記事 JavaScript関係(1年目以降〜) パッケージ関係(1年目以降〜) Homebrewの記事 Composerの記事
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Error]Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails

はじめに この記事はプログラミング初学者による備忘録用の記事であり、また、少しでも他の初学者のお役に立てればと思い書いています。 今回は、外部キー制約があるテーブルデータの削除を試みた際に、[Error]Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint failsというエラーが発生しましたので解決策を記録しておきます。 間違いなどがございましたら、ご指摘のほどよろしくお願い致します。 結論 ・新規作成する場合 onDelete('cascade')を使用して「デリート時(on delete)」に対する処理をオプションとして指定する。 Schema::create('articles', function (Blueprint $table) { //略 $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); //略 ・既にテーブルを作成している場合 外部キーを削除した後に再度外部キー制約を設定し直す。 Laravel では、 dropForeign() メソッドで外部キー制約の削除が可能である。 引数に配列値を渡せば、削除時に自動的に命名規則に従った名前が使用されます。 dropForeign() メソッドで削除後、再度外部キー制約をonDelete('cascade')付きで設定する。 example.php //略 Schema::table('articles', function (Blueprint $table) { $table->dropForeign(['user_id']); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); }); //略 エラーの原因 public function up() { Schema::create('articles', function (Blueprint $table) { //略 $table->foreign('user_id')->references('id')->on('users'); }); } //略 上記のように、テーブル作成時にonDelete('cascade')の使用を忘れていた。 まとめ 外部キー制約にonDelete('cascade')を設定することで、削除するレコードに紐づいている複数のレコードもまとめて一括で削除が可能になる。 参考文献 ・公式ドキュメント6.x データベース マイグレーション
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

laravel new で Laravelを始めるまでの記録

はじめに この資料は、 laravel new コマンドを使うために行った設定諸々のメモです。 参考になればと思います。 特記事項 全てのコマンドはやった結果であり、「なぜ」については「こうやった結果うまくいっている」(必要な物を入れていった結果のまとめ)と捉えていただけたらと思います。 環境 MacOS 11.2.3 入ってるもの一覧 brew phpbrew (過去に入れたことがあるやつが入ってた) やったこと 事前準備的なもの phpbrew 更新 とりあえず最新化で。 phpbrew self-update 必要なパッケージのインストール brew でインストール。 brew install phpbrew でPHPインストール phpbrew i 7.4.19 +bz2="$(brew --prefix bzip2)" +zlib="$(brew --prefix zlib)" phpbrew switch 7.4.19 phpbrew known --update で有効なバージョンを確認できます。 確認 $ php -v PHP 7.4.19 (cli) (built: May 10 2021 21:09:33) ( NTS ) Copyright (c) The PHP Group Zend Engine v3.4.0, Copyright (c) Zend Technologies $ 拡張モジュールをインストール phpbrew ext install iconv mbstring json curl filter openssl fileinfo 次の laravel new でモジュールエラーになった場合に、このコマンドで入れます。(エラーになって入れてを繰り返した結果がこちらです) Laravel インストール laravel new api api は、任意の名前です。 成功したら /api 以下にLaravel モジュールが出来上がります。 確認 php artisan serve で、ブラウザから http://localhost:8000 とアクセスし、Laravelのページが表示できたらOK。 以降、Laravel に必要な個別設定を行ってください!!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【TP転職市場PJ日記その4】アカウント設定のバリデーションから検索画面まで頑張る回

前回は... Laravel Jetstream を使ってアカウント発行管理系の仕組みを簡単に導入したね。 今回は導入後のアカウントの設定画面やら独自バリデーション(入力チェック)とか検索系の実装で頑張った回を書いてく Laravel Jetstream便利すぎということでLet'sカスタマイズ アカウントのパスワード再発行とか自動でつくってくれるのは熱かった。 さて、これに今回のwebサービスに合うようにカスタマイズしますよっと… 結論こんな感じの画面にしました。 ・氏名(これ書いてるときに思ったけどユーザー名でいいなw) ・メアド(認証系でどうしても必要) ・ユーザー区分:プレイヤー(TPチームの選手だけやってるならこれだけチェック) ・ユーザー区分:チーム運営者(TPチームの運営だけやってるならこれだけチェック、もちろんプレイヤー兼運用の場合は両方チェック) ・所属チーム:TPの現在所属しているチームがあればここも設定。 ※いったんこのTP転職市場でもチーム名ぐらいは管理というかデータとしてもっておきたいなと。 あ、TwitterId入れてもらう欄忘れてるな。後でつくっとこww あと、スクショ外にあるけどアカウント削除とかのボタンも用意してある。自分の始末は自分でしよーねスタイル。 嫌いじゃない。 アカウント情報の設定画面で防ぎたい事 TPチームの運営も誰でもなれるようにすると、悪意あるユーザが他チームの関係者を装って暇つぶしされても困るので 運営人数の上限を設けてその人数以上の人間は設定できないようにする事にする。 運営者の人数が増減する場合は一応アカウント削除時に上限を減らして増やしてほしかったらお願いしてねスタイルにしようかなと思う。 追々フォームで自動化したいけど今は工数がないかなー。 技術的な話 さて、このJetstreamに独自のバリデーションを追加したいが思うような情報が転がっていなかった。はて… という事で純粋にLaravelが標準で用意しているバリデーションを使えないかやってみる。 まずjetstreamのクラスについて調査でまじめにリファレンスを読む Laravel jetstreamのリファレンス こいつによると以下のクラスがUserテーブルを更新する際に使われるクラスとの事でこいつの改修をしてみることに UpdateUserProfileInformation.php <?php namespace App\Actions\Fortify; use App\Models\User; use App\Rules\TeamValidRules; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; use Laravel\Fortify\Contracts\UpdatesUserProfileInformation; class UpdateUserProfileInformation implements UpdatesUserProfileInformation { /** * Validate and update the given user's profile information. * * @param mixed $user * @param array $input * @return void */ public function update($user, array $input) { Validator::make($input, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)], 'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:1024'], ])->validateWithBag('updateProfileInformation'); if (isset($input['photo'])) { $user->updateProfilePhoto($input['photo']); } if ($input['email'] !== $user->email && $user instanceof MustVerifyEmail) { $this->updateVerifiedUser($user, $input); } else { $user->forceFill([ 'name' => $input['name'], 'email' => $input['email'], 'playerflag'=> $input['playerflag'], 'teammanagementflag'=> $input['teammanagementflag'], 'teamid'=> $input['teamid'] !== "" ? $input['teamid']: null, ])->save(); } } で、まずはコレ でRulsを継承したクラスを作成してロジックを書いて(ここは共有したくないw) 最終的に更新メソッドはこんな感じに(ちなみに作ったクラス名はTeamValidRulesというやつ UpdateUserProfileInformation.php <?php namespace App\Actions\Fortify; use App\Models\User; use App\Rules\TeamValidRules; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Support\Facades\Validator; use Illuminate\Validation\Rule; use Laravel\Fortify\Contracts\UpdatesUserProfileInformation; class UpdateUserProfileInformation implements UpdatesUserProfileInformation { /** * Validate and update the given user's profile information. * * @param mixed $user * @param array $input * @return void */ public function update($user, array $input) { Validator::make($input, [ 'name' => ['required', 'string', 'max:255'], 'email' => ['required', 'email', 'max:255', Rule::unique('users')->ignore($user->id)], 'photo' => ['nullable', 'mimes:jpg,jpeg,png', 'max:1024'], 'teamid' => [ new TeamValidRules($input) ], // ここを追加 ])->validateWithBag('updateProfileInformation'); if (isset($input['photo'])) { $user->updateProfilePhoto($input['photo']); } これで、自前で作った入力チェックの処理が呼ばれてエラーがあったら更新しないようにしてくれた。 jetstreamで入力チェックはこんな感じでよさげ。 そして検索画面 ここはjetstreamのrouteで遷移先を指定してコントローラー作ってって感じでできたそして 画面にはテンプレートサイトから無料な物を引っ張ってきたんだが、できればjetstreamのメニューアイコンなどは使いたいということで jetstreamの仕組みを利用することに。最低限こんな感じのタグ構成でいってみたらいい感じになった。 xxx.blade.php <x-app-layout> <div>templatebody</div> <div>templatebody</div> <div>templatebody</div> <div>templatebody</div> </x-app-layout> <x-app-layout> っていうのでかこってあげるとjetstreamのテンプレートいい感じにマージしてくれるみたい。 (さっきからいい感じにしか書いてない気がするww) 検索画面の仕様 ・非同期はしない工数の関係でゴメン。POSTでやる。 ・初期表示は全件検索ページネーション付きでやる。 ・フィルター条件はポジションとin率と所属チームor所属リーグ ・ソートはつけるけど降順指定 ※このあたりはTPやってる人の意見を追って聞いてみたいと思う。 というわけで画面は鬼質素。こう。目的特化型です。募集してる人、チームが見つかればええねん。 Twitterでやってるんだから。見た目もク〇もあったもんじゃないでしょ。すみません。スピード感優先で質素なだけです。ごめんなさい。 次回は... ユーザー検索画面から詳細画面へそして気になる&スカウトボタンと評価の見える化というか気になるボタンやスカウトの通知を実装していこうと思ふ。 なんか記事かくよりも早く実装したくてウイイレどころじゃないw ってわけで開発頑張ります^^ また次回お願いします^^
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel mimetypesでバリデーション設定したら突破するはずの値が弾かれる

目的 mimetypesのバリデーションルールを設定後にバリデーションを通過するはずの値が弾かれる問題の原因をまとめる 原因 Mimetypeの指定時にスペースを入れてしまっていた。 問題のソース 下記のようにバリデーションルールを記載した。 アプリ名ディレクトリ/todos/app/Http/Requests/TaskRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class TaskRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => ['required'], 'limit_id' => ['required'], 'file' => [ 'required', 'file', 'image', 'mimetypes: image/jpeg, image/png', ], ]; } } 注目いただきたいソースは'mimetypes: image/jpeg, image/png',の部分であり、Mimetype名の前に半角スペースが空いている。これが原因だった。 問題を解消したソース 下記のようにバリデーションルールを記載した。 アプリ名ディレクトリ/todos/app/Http/Requests/TaskRequest.php <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class TaskRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'name' => ['required'], 'limit_id' => ['required'], 'file' => [ 'required', 'file', 'image', 'mimetypes:image/jpeg,image/png', ], ]; } } 上記のように半角スペースを開けずに記載することでバリデーションを突破する事ができた。 参考文献 https://developer.mozilla.org/ja/docs/Web/HTTP/Basics_of_HTTP/MIME_types
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む