20210610のlaravelに関する記事は8件です。

Laravel 課題2・メールアドレス帳の作成

csvファイル storage/app/address_list.csv 山田太郎,東京都港区,t.yamada@test.com 佐藤花子,東京都杉並区,h.sato@test.com 山本二郎,東京都豊島区,j.yamamoto@test.com 田中三郎,神奈川県横浜市,s.tanaka@test.com 斎藤さくら,東京都台東区,s.saitou@test.com 加藤桃,東京都世田谷区,m.kato@test.com k,k,k ルーティング /routes/web.php <?php Route::get('/address_list', 'SampleController@addressList'); Route::post('/address_list', 'SampleController@addressWrite'); コントローラー app/Http/Controllers/SampleController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SampleController extends Controller{ public function addressList(){ // SplFileObjectの作成 $file = new \SplFileObject(storage_path('app/address_list.csv')); // 読み込み設定 $file->setFlags( \SplFileObject::READ_CSV | // CSVを配列形式で読み込む \SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY | // 前の行と合わせて、空行があったら読み飛ばす \SplFileObject::DROP_NEW_LINE // 改行コードは無視する ); // 1行ずつ読み込んで配列に保存 $members = []; foreach($file as $member){ $members[] = $member; } return view('samples.address_list', [ 'title' => 'メールアドレス帳', 'members' => $members, ]); } // ----書き込み------------------------------------------------------------------- public function addressWrite(Request $request){ // SplFileObjectを追記モードで作成 $file = new \SplFileObject(storage_path('app/address_list.csv'), 'a'); // 送信データから書き込み用の配列を作成 $member = [ $request->input('name'), $request->input('address'), $request->input('mail'), ]; // csvファイルに書き込み $file->fputcsv($member); // 一覧表示画面にリダイレクト return redirect('/address_list'); } } ビュー resources/views/samples/csv_sample.blade.php @extends('layouts.default') @section('title', $title) @section('content') <h1>{{ $title }}</h1> <form method="post" action="{{ url('/address_list') }}"> @csrf <div> <label> 名前: <input type="text" name="name"> </label> </div> <div> <label> 住所: <input type="text" name="address"> </label> </div> <div> <label> メールアドレス: <input type="text" name="mail"> </label> </div> <div> <input type="submit" name="登録"> </div> </form> <table> <tr> <th>名前</th> <th>住所</th> <th>メールアドレス</th> </tr> @foreach($members as $member) <tr> <td> {{ $member[0] }} </td> <td> {{ $member[1] }} </td> <td> {{ $member[2] }} </td> </tr> @endforeach </table> @endsection 共通レイアウトファイル <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>@yield('title')</title> <style> .header_nav { display: flex; list-style: none; padding-left: 0; } .header_nav li { margin-right: 30px; } /* エラーメッセージ用のスタイル */ .error { color: red; } </style> </head> <body> @yield('header') {{-- エラーメッセージを出力 --}} @foreach($errors->all() as $error) <p class="error">{{ $error }}</p> @endforeach @yield('content') </body> </html>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

laravel クッキーのサンプル

ルーティング /routes/web.php <?php Route::get('/cookie_sample', 'SampleController@cookieSample'); Route::post('/cookie_sample', 'SampleController@cookieDelete'); コントローラー app/Http/Controllers/SampleController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SampleController extends Controller{ public function cookieSample(){ $count = \Cookie::get('count', 0); $count++; \Cookie::queue('count', $count, 60 * 24 * 90); return view('samples.counter_sample', [ 'title' => 'クッキーを利用するサンプル', 'count' => $count, ]); } public function cookieDelete(){ \Cookie::queue(\Cookie::forget('count')); return 'cookieを削除しました。'; } } ビュー resources/views/samples/csv_sample.blade.php @extends('layouts.default') @section('title', $title) @section('content') <h1>{{ $title }}</h1> @if($count === 1) <p>初めての訪問です。</p> @else <p>{{ $count }}回目の訪問です。 @endif <form method="post"> @csrf <input type="submit" value="履歴を削除"> </form> @endsection 共通レイアウトファイル <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>@yield('title')</title> <style> .header_nav { display: flex; list-style: none; padding-left: 0; } .header_nav li { margin-right: 30px; } /* エラーメッセージ用のスタイル */ .error { color: red; } </style> </head> <body> @yield('header') {{-- エラーメッセージを出力 --}} @foreach($errors->all() as $error) <p class="error">{{ $error }}</p> @endforeach @yield('content') </body> </html>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

laravel バリデーション

ルーティング /routes/web.php <?php Route::get('/validation_sample', 'SampleController@validationSampleForm'); Route::post('/validation_sample', 'SampleController@validationSample'); コントローラー app/Http/Controllers/SampleController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SampleController extends Controller{ public function validationSampleForm(){ return view('samples.validation_sample_form', [ 'title' => 'バリデーション用サンプルフォーム', ]); } public function validationSample(Request $request){ $request->validate([ // ここに項目ごとのバリデーションルールを記述 'name' => ['required', 'min:2', 'max:20'], 'user_name' => ['required', 'min:3', 'max:20'], 'email' => ['required', 'email'], 'age' => ['required', 'integer', 'min:16', 'max:150'], 'birthdate' => ['required', 'date', 'before:now', 'after_or_equal:1900-1-1'], ]); return redirect('/validation_sample'); } } ビュー resources/views/samples/validation_sample_form.blade.php @extends('layouts.default') @section('title', $title) @section('content') <h1>{{ $title }}</h1> <form method="post"> @csrf <div> <label> 名前: <input type="text" name="name"> </label> </div> <div> <label> 名前(ふりがな): <input type="text" name="name_kana"> </label> </div> <div> <label> ユーザー名(アルファベットor数字): <input type="text" name="user_name"> </label> </div> <div> <label> メールアドレス: <input type="text" name="email"> </label> </div> <div> <label> 年齢: <input type="text" name="age"> </label> </div> <div> <label> 生年月日: <input type="date" name="birthdate"> </label> </div> <div> <label> 住所: <input type="text" name="address"> </label> </div> <div> <label> 電話番号: <input type="text" name="phone"> </label> </div> <div> <label> プライバシーポリシーに同意します: <input type="checkbox" name="policy"> </label> </div> <div> <input type="submit" value="登録"> </div> </form> @endsection 共通レイアウトファイル <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <title>@yield('title')</title> <style> .header_nav { display: flex; list-style: none; padding-left: 0; } .header_nav li { margin-right: 30px; } /* エラーメッセージ用のスタイル */ .error { color: red; } </style> </head> <body> @yield('header') {{-- エラーメッセージを出力 --}} @foreach($errors->all() as $error) <p class="error">{{ $error }}</p> @endforeach @yield('content') </body> </html>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laradock環境におけるClass 'Pusher' not found のエラーについて

はじめに Laradock環境でLaravelアプリに通知機能を付けたい方向けに、タイトルのエラーが生じた場合の対処について記載しました。 Pusherの登録と.envの記述を済ませた後... laradockディレクトリ下で以下を実行 $ docker-compose exec workspace composer require pusher/pusher-php-server すると以下の表示が、、、 Fatal error: Allowed memory size of 1610612736 bytes exhausted 略 単純に容量の問題かな?と思い、以下を実行してコンテナ内へ $ docker-compose exec workspace bash コンテナに入り、root@xxx:/var/www/html下で以下を実行 $ COMPOSER_MEMORY_LIMIT=-1 composer require pusher/pusher-php-server しかし上手くいかず何故か killedで強制的に追い出される、、、 composerコマンドはLaradock下ではなくLaravel下で ここでlaradock下で実行するのが適切でないのでは?と思い、laravelディレクトリ下で以下を実行 $ composer require pusher/pusher-php-server すると以下の表示が、、、 Problem 1 - Root composer.json requires barryvdh/laravel-debugbar ^3.6, found barryvdh/laravel-debugbar[v3.6.0, v3.6.1] but the package is fixed to v3.5.7 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command. どうやらcomposer.lockに記述されているbarryvdh/laravel-debugbaのバージョンがv3.5.7では噛み合わず、v3.6系に変えてくれ、ということらしい。 composer.lockに記述を以下のように書き換えた "packages-dev": [ { "name": "barryvdh/laravel-debugbar", "version": "v3.6.1", //v3.5.7からv3.6.1へ書き換え "source": { "type": "git", "url": "https://github.com/barryvdh/laravel-debugbar.git", //略 }, 結果、以下が通り、Class 'Pusher\Pusher' not foundの問題が解決!!! $ composer require pusher/pusher-php-server --with-all-dependencies 以上です。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

laravel モデルのテーブル名を取得する

目的 laravelのモデルからテーブル名を取得する方法をまとめる 方法 下記のように記載することで$tableNameにテーブル名が格納される。(下記ソースに記載されていないが、モデルが依存注入されているものとする。) $tableName = $this->モデル->getTable(); モデルのgetTable()を実行すればテーブル名が返される。 参考文献 https://github.com/laravel/framework/issues/1436
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel エラー辞書(自分用)

Target class [PostController] does not exist. コントローラが見つからない。 解決策①:ルートのpassを確認 web.phpのnamespaceを完全にに指定する。 App\Http\Controllers\を追加して完全に指定 web.php Route::get('/home', 'HomeController@index')->name('home'); web.php Route::get('/home', 'App\Http\Controllers\HomeController@index')->name('home');
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel routes→Controller→view

Laravel6における、routes→Controller→viewの基本的な流れをメモ。 routes Route::get('/', function () { return view('welcome'); }); Route::get('/home', 'HomeController@index')->name('home'); Route::get('[view名](ディレクトリ/ファイル)',[Controller名]'@[method名]')->name('[リンク名をつける](controller名.method名)など'); Controller public function index() { //クエリビルダ $hoges = DB::table('log_me_events') ->select('id', ...)//取得したいカラム ->orderBy('year', 'desc')//ソートをかけたり ->get();//最終データベースから取得する return view('[view名](ディレクトリ.ファイル)', compact('')); } view @foreach($hoges as $hoge) <tr> <td>{{$hoge->id}}</td> <td>{{$hoge->...}}</td> </tr> @endforeach
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Laravel] $fillableと$guarded/モデルの追加と更新まとめ

はじめに モデルの追加や更新を行う方法がいくつかあるため(さまざまな記事で見かけます)、この際にまとめ、「どれがベストなのか」自分なりの結論を出したいと思いました。 検証環境 macOS Catalina ver 10.15.7 Docker ver 20.10.5 docker-compose ver 1.29.0 Laravel ver 7.30.4 MySQL ver 8.20.3 $fillableと$guarded 「僕がLaravelのEloquentに$fillableでなく$guardedを指定する理由」をまずお読みください。 こちらに\$fillableと\$guardedについて書かれています。 当然ですが、create()やupdate()、fill()を使用する際に\$fillableまたは\$guardedのどちらかを定義していないとエラーになります。 $fillableのメリットとデメリット メリット 指定したカラムのみ値の操作を許可する。 デメリット カラムが増えるたびにその都度、付け加えなければならない。 $guardedのメリットとデメリット メリット 値の操作を禁止するカラムだけを指定すれば良いので、カラムが増えても、その都度\$guardedに加えなくて良い(\$guardedとして定義したいカラムが増えれば、都度付け加えなければなりませんが...)。 デメリット 指定したカラム以外、値の操作が行われるので、$guardedのみ見た場合、他のどのカラムの操作が許可されているか把握しづらい。 私は\$guardedを見て、「他に指定するべきカラムがあるかな~」と心配になるので、「見てすぐわからない」というのは心配性には不向きだと思います。 モデルの追加と更新 追加 $this->カラム = データでのやり方 書くのが面倒 \$fillableまたは\$guardedを無視する PostController.php $post = new Post(); $post->store($data); // storeは自分で定義したもの Post.php public function store($data) { $this->title = $data['title']; $this->content = $data['content']; $this->save(); } モデル::createでのやり方 簡潔で見やすい \$fillableまたは\$guardedを確認する PostController.php Post::create($data); 更新 $this->カラム = データでのやり方 こちらも書くのが面倒 \$fillableまたは\$guardedを無視する PostController.php $post->updateContents($data); //updateContentsは自分で定義したもの Post.php public function updateContents($data) { $this->title = $data['title']; $this->title = $data['content']; $this->save(); } update() 簡潔で見やすい \$fillableまたは\$guardedを確認する しかし、「LaravelのORMで初心者から職人へ」にも書いてある通り、直接SQLでデータを入れているため危険であることは認識しなければならない。 PostController.php $post->update($data); fill($data)->save()は追加と更新のどちらも可能 追加 \$post->fill(\$data)->save() インスタンスを作成するのが面倒 \$fillableまたは\$guardedを確認する PostController.php $post = new Post(); $post->fill($data)->save(); 更新 \$post->fill(\$data)->save() \$fillableまたは\$guardedを確認する update()との違いは、「Eloquentのメソッド saveとupdateは処理が異なる」を参照してください。 PostController.php $post->fill($data)->save(); 上記を検討した上で、私が思うモデルの追加と更新を行う時のベストな方法 追加 モデル::create() 更新 fill($data)->save() さいごに いかがだったでしょうか。 まず、\$fillableと\$guardedについてですが、私は\$fillableの方が\$guardedより良いのではないかと考えます。なぜなら、繰り返しになりますが、すべてのカラムを把握しなくとも「どのカラムに対して値の操作が許可されているか」見てすぐわかるからです。 次にモデルの追加や更新を行う方法を述べ、それぞれいくつかあることを確認しました。 私と同じく「そのような方法があったんだ!」と新たな発見をし、自身のコードを見直すきっかけになれれば幸いです。 ご指摘およびご意見お待ちしております。 それではまた! 参考サイト 「LaravelのORMで初心者から職人へ」 https://qiita.com/henriquebremenkanp/items/cd13944b0281297217a9 「僕がLaravelのEloquentに\$fillableでなく\$guardedを指定する理由」 https://qiita.com/toro_ponz/items/b33c757cb7ba5bb48ed4 「Eloquentのメソッド saveとupdateは処理が異なる」 https://qiita.com/gomaaa/items/91e5cbd319279a2db6ec
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む