20210606のlaravelに関する記事は10件です。

JetStreamのUpdateProfileInformationFormの拡張方法

ことはじめ Laravelのユーザー認証ライブラリにある「JetStream」便利ですよね。 コマンド一発でそれっぽい画面が出来てテーブルも出来上がって素敵ですよね。 ただ、必要な項目はそれなりにそろっていても独自に拡張したいことはあるはず。 今日はアカウント設定周りでの拡張方法について学んだ事をシェア。 前提として「JetStream」導入済みかつカスタマイズしたい方向けのお話になります。 今回こんなことを更新画面でカスタマイズしたい。 更新画面であらかじめマスターデータを取得、プルダウンリストにしてユーザーに選択させたい はい、よくあるやつですよね。「JetStream」ライブラリのカスタマイズはlaravelのリファレンスにも 用意はされてましたね。artisan コマンドでpublishしてあげると、view側のカスタマイズはできるような書きっぷり ですね。 php artisan vendor:publish --tag=jetstream-views でも今回治したいのはview側ではなくサーバー側のロジック修正したい。 grepしてみると初期表示周りはUpdateProfileInformationForm.phpが修正箇所みたい。 手順ものっていなく詰んだっぽい…検索してみた。 結論この参考サイトで救われた どうやら同じように拡張したいけど、やり方わからんという仲間がいて そして猛者が回答してくれている。ありがとう。 それによると、 app\Http\配下にLivewireフォルダーを作成する。 作成したLivewireフォルダーにUpdateProfileInformationForm.phpを作成する \vendor\laravel\jetstream\src\Http\Livewire\UpdateProfileInformationForm.php を作成したファイルにコピーする  ※namespaceとかは適宜置き換えてね。 JetstreamServiceProvider.php の boot メソッドに作成したファイルを指定する。 JetstreamServiceProvider.php <?php namespace App\Providers; use App\Actions\Jetstream\DeleteUser; use Illuminate\Support\ServiceProvider; use Laravel\Jetstream\Jetstream; use App\Http\Livewire\UpdateProfileInformationForm; // こいつが追加したやつ use Livewire\Livewire; class JetstreamServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { $this->configurePermissions(); Livewire::component('profile.update-profile-information-form' , UpdateProfileInformationForm::class); // 追加 Jetstream::deleteUsersUsing(DeleteUser::class); } } 動作確認 作成したファイルUpdateProfileInformationForm.phpにddで何かしら書いて呼ばれているか確認すると 良い。 ちなみに 画面への連携も書いておく。こんな感じに書いておくと画面に連携されてきます。 UpdateProfileInformationForm.php <?php namespace App\Http\Livewire; use Illuminate\Support\Facades\Auth; use Laravel\Fortify\Contracts\UpdatesUserProfileInformation; use Livewire\Component; use Livewire\WithFileUploads; class UpdateProfileInformationForm extends Component { use WithFileUploads; // 色々省略 /** * Prepare the component. * * @return void */ public function mount() { $this->state = Auth::user()->withoutRelations()->toArray(); $sample[] = array('list1'=>'リストa'); $sample[] = array('list1'=>'リストb'); $sample[] = array('list1'=>'リストc'); $this->sample = $sample; } // 色々省略 } update-profile-information-form.blade.php <x-jet-form-section submit="updateProfileInformation"> <x-slot name="title"> {{ __('Profile Information') }} </x-slot> <x-slot name="description"> {{ __('Update your account\'s profile information and email address.') }} </x-slot> <x-slot name="form"> <!-- Name --> <div class="col-span-6 sm:col-span-4"> <x-jet-label for="name" value="{{ __('Name') }}" /> <x-jet-input id="name" type="text" class="mt-1 block w-full" wire:model.defer="state.name" autocomplete="name" /> <x-jet-input-error for="name" class="mt-2" /> </div> <!-- Email --> <div class="col-span-6 sm:col-span-4"> <x-jet-label for="email" value="{{ __('Email') }}" /> <x-jet-input id="email" type="email" class="mt-1 block w-full" wire:model.defer="state.email" /> <x-jet-input-error for="email" class="mt-2" /> </div> <!-- sample--> <div class="col-span-6 sm:col-span-4"> <x-jet-label for="sample" value="所属チーム" /> <select id="sample" wire:model.defer="state.sample" lass="block w-full border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50 rounded-md shadow-sm"> <option value="">null</option> @foreach ($this->sample as $row) <option value="{{ $row['list1'] }}"> {{ $row['list1'] }}</option> @endforeach </select> <x-jet-input-error for="sample" class="mt-2" /> </div> </x-slot> </x-jet-form-section>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelルートパラメータ解説

ルートパラメータとはURLのパスの設定の事である。 ルーティング <?php Route::get('/route_parameter/{id_01}/comments/{id_02}', 'SampleController@routeParameter'); コントローラー <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SampleController extends Controller { public function routeParameter($id_011, $id_021){ return view('samples.route_parameter', [ 'title' => 'ルートパラメータのサンプル', 'id_0111' => $id_011, 'id_0211' => $id_021, ]); } } ビュー @extends('layouts.default') @section('title', $title) @section('content') <h1>{{ $title }}</h1> <p>id: {{ $id_0111 }}</p> <p>comment_id: {{ $id_0211 }}</p> @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; } </style> </head> <body> @yield('header') @yield('content') </body> </html>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel ルーティング・コントローラー組み合わせ、簡単なプロフィール

ルーティング <?php Route::get('/show_profile', 'ShowProfile'); コントローラー <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class ShowProfile extends Controller { function __invoke(){ $title = 'プロフィール'; $name = '山田 太郎'; $address = '東京都港区六本木'; $skill = '寝付きが良い'; return view('samples.show_profile', [ 'title' => $title, 'name' => $name, 'address' => $address, 'skill' => $skill, ]); } } レイアウトファイル @extends('layouts.logged_in') @section('title', $title) @section('content') <h1>{{ $title }}</h1> <dl> <dt>名前</dt> <dd>{{ $name }}</dd> <dt>住所</dt> <dd>{{ $address}}</dd> <dt>特技</dt> <dd>{{ $skill }}</dd> </dl> @endsection レイアウトファイル(ログイン後用) @extends('layouts.default') @section('header') <header> <ul class="header_nav"> <li>このサイトについて</li> <li>ユーザー設定</li> <li>プライバシーポリシー</li> <li>ログアウト</li> </ul> </header> @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; } </style> </head> <body> @yield('header') @yield('content') </body> </html>
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Gitコマンドについて(よく使うもの)

gitコマンド ローカルリポジトリからリモートリポジトリへと、記入する順に紹介します。 (※事前にGitHubでリモートリポジトリを作成しているか確認してください。) リポジトリを新規作成 Terminal $ git init コミット対象のファイルを登録 Terminal $ git add トラッキング状態にしたいファイル名 //指定したファイルのみ $ git add . //ディレクトリ配下すべてのファイル トラッキング状態にするコマンド。 コミットしたときに登録できるよう、ステージング領域に一時保存されます。 変更されたファイルをコミット Terminal $ git commit -m "コミットメッセージ" //変更履歴にコミットメッセージが付属する トラッキング状態にあるファイルがリポジトリに保存されます。 コミット履歴を表示 Terminal $ git log 今までのコミットした履歴を表示できます。 表示内容は、コミットID、変更者の氏名・メールアドレス(基本的に自分の情報)、変更日時、コミット時に入力したコミットメッセージだそうです。 リポジトリをコピー Terminal $ git clone これは使ったことがないので、また後日詳しく調べることにします。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Hotpepperのapiを使ってお店の情報を表示してみた

はじめに 転職活動の面接で「WebApi使ったことある?」と聞かれ、全く経験のなかった僕はドラクエのさまようたましいのようにまごまごしてしまったため、この機会に何かのAPIを使ってみようと思いました。 今回はリクルートが提供しているhotpepperのAPIを利用して、我が本拠地横浜のレストラン情報を取得してみました。 そもそもWebAPIとは? APIとは、「Application Programming Interface」の頭文字をとったもので、インターフェースと言う時からも何となくわかるように、プログラムがサービスを利用する窓口のことを言います。 Web APIの場合、プログラムはWeb上に公開され、外部から呼び出して利用します。その多くは無料で私たちも利用することができます。 実際にHotpepperのAPIでレストランの情報を取得して表示してみた 開発環境 PHP:7.3.11 Laravel:7.30.4 Guzzle: 7.3 リクルートWEBサービスへ新規登録 こちらよりメールアドレス のみで無料登録し、APIキーを取得します。登録したメールアドレス宛にすぐ届きます。 laravelのプロジェクトを作成 ターミナルから新たにプロジェクトを作成します。 すでに練習用のプロジェクトがある場合は必要ありません。 $ composer create-project --prefer-dist laravel/laravel hotpepperApi "6.*" Guzzleのインストール Guzzle は、HTTP リクエストの送信を容易にし、Web サービスと簡単に統合できる PHP HTTP クライアントです。 $ composer require guzzlehttp/guzzle APIのの設定をenv.ファイルに追記します。 MIX_PUSHER_APP_KEY="${PUSHER_APP_KEY}" MIX_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}" HOTPEPPER_API_KEY=1111a1a1aaaa1a11 // ここにAPI登録時に取得したAPIキーをペースト 本番環境で env.ファイルは読み込まれないので、config配下にhotpepper.phpを作成。 ModelやContorllerから、configメソッドで呼び出せるようにします。 <?php return [ 'api_key' => env('HOTPEPPER_API_KEY') ]; これでconfig('hotpepper.api_key')でどこからでも呼び出せるようになりました。 コントローラーに店舗情報を取得できるよう実装していく GETメソッドでAPIを利用してみます。 HotpepperのAPIを叩いて、横浜のタがついた店舗情報10件取得してみよう 任意のコントーラーを作成して記述してみる。 ひとまずHotpepperControllerを作成。 <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use GuzzleHttp\Client; // ここを追記 class HotpepperController extends Controller { // HTTPリクエストを送るURL private const REQUEST_URL = 'http://webservice.recruit.co.jp/hotpepper/gourmet/v1/'; // APIキー private $api_key; public function index() { // インスタンス生成 $client = new Client(); // HTTPリクエストメソッド $method = 'GET'; // APIキーを取得 $this->api_key = config('hotpepper.api_key'); // APIキーや検索ワードなどの設定を記述 $options = [ 'query' => [ 'key' => config('hotpepper.api_key'), 'keyword' => '浦安', 'count' => 10, 'format' => 'json', ], ]; // HTTPリクエストを送信 $response = $client->request($method, self::REQUEST_URL, $options); // 'format' => 'json'としたのでJSON形式でデータが返ってくるので、連想配列型のオブジェクトに変換 $restaurants = json_decode($response->getBody(), true)['results']; // dd($restaurants); // index.blade.phpを表示する return view('index', compact('restaurants')); } } 以下のように記述することでAPIに対してGETメソッドでHTTP通信を行うことができる $client = new Client(); $response = $client->request([メソッド], [アクセスしたいURL]); ルーティングの設定も忘れずに。 URL/homeだったらHotpperControllerのindexアクションへ web.php Route::get('/home', 'HotpepperController@index'); 店舗情報を取得してみた 結果を表示するviewは、index.blede.phpを新たに作成します。 取得した値は配列に変換しているため、$restrants['name']のような記述で値を表示することが可能です。 <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>ホットペッパーAPI</title> </head> <body> <table border="1"> <tr> <th>店舗名</th> <th>営業時間</th> </tr> @for ($i = 0; $i < $restaurants['results_returned']; $i++) <tr> <td><a href="{{{ $restaurants['shop'][$i]['urls']['pc'] }}}">{{{ $restaurants['shop'][$i]['name'] }}}</a></td> <td>{{{ $restaurants['shop'][$i]['open'] }}}</td> </tr> @endfor </table> </body> </html> こんな感じで取得できました! おわりに はじめてWebAPIを使ってみて、こんな簡単に情報を取得できることに感動しました。 世の中には無料で提供されているAPIがごまんとあるようなので他のものも使ってみたいですね! 参考
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelのパスワードリセットをemail以外のカラムで行うようにする

はじめに Laravelの標準のAuthのパスワードリセットでは、emailのカラムを元にリセットを行いますが、別のカラムを元にリセットをしたい場合など、パスワードリセットの機能をオーバーライドする必要が出てきます。 今回はパスワードリセットの機能についてつまづいた部分を書き留めておきたいと思います。 なお、本記事ではemailではなくmail_addressというカラムを使って実装していますので、適宜置き換えて実装してもらえればと思います。 使用しているLaravelのバージョンは5.7.29です。 ForgotPasswordControllerのオーバーライド emailではなくmail_addressというカラムを使うようにForgotPasswordControllerのオーバーライドします。 email.blade.phpで送られるパラメータをmail_addressに変更します。 resources/views/auth/passwords/email.blade.php <form method="POST" action="{{ route('password.email') }}"> @csrf <div class="form-group"> <label for="mail_address">{{ __('メールアドレス') }}</label> {{ Form::text('mail_address', null, ['class' => 'form-control']) }} @if ($errors->has('mail_address')) <span class="invalid-feedback" role="alert"> <strong>{{ $errors->first('mail_address') }}</strong> </span> @endif </div> {{ Form::submit(__('送信'), ['class' => 'btn btn-primary']) }} </form> mail_addressの項目を使うようにsendResetLinkEmailをオーバーライドします。 app/Http/Controllers/Auth/ForgotPasswordController.php public function sendResetLinkEmail(Request $request) { $this->validate($request, ['mail_address' => 'required'], ['mail_address.required' => 'メールアドレスを入力してください。']); $response = $this->broker()->sendResetLink( $request->only('mail_address') ); if ($response === Password::RESET_LINK_SENT) { return back()->with('status', trans($response)); } return back()->withErrors( ['mail_address' => trans($response)] ); } ここまでで、リクエストパラメータのバリデーションとユーザー検索の処理を mail_address を使って行えようになります。 次に password_resets テーブルにinsertするパラメータの取得を email から mail_address に変更します。 app/User.php public function getEmailForPasswordReset() { return $this->mail_address; } 最後にメール送信するパラメータの取得を変更します。 app/User.php public function routeNotificationForMail() { return $this->mail_address; } これでメール送信までできるようになりました。 ResetPasswordControllerのオーバーライド 最後にパスワード変更を行なっているメソッドのをしていきます。 下記のようにreset.blade.phpで送るパラメータをmail_addressに変更します。 resources/views/auth/passwords/reset.blade.php <input type="hidden" name="mail_address" value="{{ $email ?? old('email') }}" required autofocus> ResetPasswordControllerのcredentialsをオーバーライドしてmail_addressを元にユーザーの検索を行うようにします。 app/Http/Controllers/Auth/ResetPasswordController.php protected function credentials(Request $request) { return $request->only( 'mail_address', 'password', 'password_confirmation', 'token' ); } これだけだとemailのバリデーションに引っかかるので、バリデーションのルールをオーバーライドします。 app/Http/Controllers/Auth/ResetPasswordController.php protected function rules() { return [ 'token' => 'required', 'mail_address' => 'required|email', 'password' => 'required|confirmed', ]; } これで、emailではなくmail_addressを使って機能するパスワードリセットの実装ができました。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelのコントローラー解説(編集中)

コントローラとは、 ルーティングからリクエストを受け取り、適切なレスポンスを返すため、各種のデータ処理を行った上でビューに必要な変数を渡す役割を持った物です。 <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SampleController extends Controller { public function sampleAction(){ $title = 'コントローラーのアクションを利用'; return view('samples.blade_example',[ 'title' => $title, ]); } } <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class SingleAction extends Controller { function __invoke(){ $title = 'シングルアクションのサンプル'; $description = 'シングルアクションコントローラを利用しています。'; return view('samples.single_action', [ 'title' => $title, 'description' => $description, ]); } }
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

[Laravel]フォームリクエストでバリデーション

フォームリクエストを活用したバリデーションの仕方。 一度実装していたのに忘れていて時間食ったのでまとめときます。 自分用に書いてるところあるので雑だったらすみません。(笑) Requestを作る php artisan make:request PostRequest PostRequestの中身 App/Http/Requests/PoseRequest <?php namespace App\Http\Requests; use Illuminate\Foundation\Http\FormRequest; class PostRequest 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 [ 'user_id' => 'required|integer', 'title' => 'required|string|max:30', 'content' => 'string', ]; } } authorizeのreturnがデフォルトではfalseになっていますが、trueに変えておきます。 ここがfalseのままだとコントローラーにリクエストが通りません。 rulesの部分にバリデーションルールを設定していきます。 PoseControllerの中身(storeアクション) PostControllerからStoreを抜粋しました。 App/Http/Controllers/PostController namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Post; use Auth; use App\Http\Requests\ReviewRequest; 〜省略〜 /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(PostRequest $request) { $post = new Post(); $post->fill($request->all())->save(); return redirect()->route('post.show', ['post'=>$post]); } use App\Http\Requests\ReviewRequest;の部分で先ほど作成したリクエストを読み込んでます。 storeアクションの引数にPostRequestを使用することでStoreアクション宛のリクエストがPostRequestを通ってくるので、そこでバリデーションが適応されます。 今回はデータの保存にfillを使用しているのでPostModelも編集しておきます。 PostModelの中身 App/Models/PostModel 〜省略〜 class Review extends Model { use HasFactory; 〜省略〜 protected $fillable = [ 'user_id', 'title', 'comment',   ]; } fillableで指定した値のみがDBに保存することを許可します。 この設定をしないとfillを使用する場合はなにも保存できなくなるので。 以上でRequestを使用したバリデーションが使用できるはずです。 参考記事
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Larabelポートフォリオ作成#1

Larabelポートフォリオ作成#1 ポートフォリオ作成記録 現在プログラミングスクールに通っていてカリキュラムが終了したので転職活動用のポートフォリオを作成することにしました。 こまめにポートフォリオ作成記録をつけていきたいと思います 作るもの 作るものは色々迷いましたが勤怠管理アプリを作ることにしました。 ここまででやっていること ・Laravelの開発環境 ・git、GitHubで開発管理準備 終わりに これからGitHubで擬似チーム開発のようにしながらポートフォリオを作成していきます
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

主キー以外を外部キーに設定する時に詰まった話

お久しぶりです、やすのりです! 今日はLaravelでテーブル作成時に詰まったので備忘録も兼ねて記事を書いていきたいと思います。 結論 外部キーと参照元カラムの設定は同じにしよう!! 何があったのか? 業務上でLaravelアプリを使用していますが、その中で新しいテーブルを3つ作って全部リレーションさせて、尚且つその内の2つは『外部キーの参照元を主キー以外に設定』する仕様になっていました。 1つ目のテーブルを作成するのは難なくできましたが...2つ目のテーブルを作成する時にエラーが出まくりました! SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (S QL: alter table `test2` add constraint `test2_test1_id_foreign` foreign key (`test1_id`) references `test1` (`test1_id`)) ※カラム名は仮称にしてあります。 とSQLの『test2テーブルのtest1_idは外部キー設定が出来ませんよ!!』というエラーが出てきました... このエラーでよく見かける解決ほうに『主キーの型と外部キーの型が間違っている』というものがありました。 そして実際のコードを見てみましょう。 public function up() { Schema::create('test1', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id')->unsigned(); $table->integer('test1_id')->unsigned()->unique(); $table->timestamps(); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); }); } public function up() { Schema::create('test2', function (Blueprint $table) { $table->increments('id'); $table->integer('test1_id'); $table->integer('test2')->unique(); $table->timestamps(); $table->foreign('test1_id') ->references('test1_id') ->on('test1'); }); } はい、この時点で分かる人には分かりますね。 そう、『test1テーブルのtest1_idに'符号なし'を意味する'unsigned'を設定しているのに、test2テーブルの外部キーである'test1_id'には設定していない』からでした! 今思えば単純なことだし、初歩的なことなんですけど... エラーが発生している時は『主キーの型と外部キーの型が間違っている』という部分に引っ張られて『え〜?主キーである'id'と'test1_id'は同じinteger型なんだけどなぁ』とか思っていました... いや、普通はそれでいいんだけど、今回は主キー以外を外部キーにしてるから『外部キーと参照元のカラムが同じ型かどうか?』を確認しないとダメでした! いやぁ、意外と初歩的なことって間違えちゃいますね!! ってことで型が間違ってないか分かりやすくするためにさっきまで使用していた『unsigned』という記述ではなくて、そもそもの型の記述を『unsignedInteger』に変更しちゃいました! public function up() { Schema::create('test1', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('user_id'); $table->unsignedInteger('test1_id')->unique(); $table->timestamps(); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); }); } public function up() { Schema::create('test2', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('test1_id'); $table->unsignedInteger('test2')->unique(); $table->timestamps(); $table->foreign('test1_id') ->references('test1_id') ->on('test1'); }); } これならパッと見で違ってたらわかるでしょう!! 感想 みなさん、初心は忘れないようにしましょう... お兄さんとの約束ですよ!!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む