質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.41%
Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

Q&A

解決済

3回答

204閲覧

Laravelで他テーブルのリストボックスを作成するには?

ratezou

総合スコア67

Laravel

LaravelとはTaylor Otwellによって開発された、オープンソースなPHPフレームワークです。Laravelはシンプルで表現的なシンタックスを持ち合わせており、ウェブアプリケーション開発の手助けをしてくれます。

0グッド

0クリップ

投稿2024/02/16 00:44

編集2024/02/16 01:03

実現したいこと

breezeのregisterに自前で作ったテーブルの項目をリストボックスを追加したいです。

発生している問題・分からないこと

初学者なもので、どう書いて良いかわからないのですが、調べたところ、
1.Modelを作成する
2.ControllerでViewに渡す
3.Viewでforeachで回す
という流れだと思うのですが、Viewを開くとforeachしようとしているコレクション?の変数が宣言されていないというエラーになります。
「Undefined variable $workplaces」となります。

該当のソースコード

```Workplace.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Workplace extends Model { use HasFactory; protected $fillable = [ 'name', ]; }

WorkplaceController.php

1<?php 2 3namespace App\Http\Controllers; 4 5use App\Models\Workplace; 6use Illuminate\Http\Request; 7 8class WorkplaceController extends Controller 9{ 10 public function getWorkplaces() 11 { 12 $workplaces = Workplace::all(); // 他のテーブルからデータを取得 13 return view('profile.edit', compact('workplaces')); 14 } 15 16 /** 17 * Display a listing of the resource. 18 */ 19 public function index() 20 { 21 // 22 } 23 24 /** 25 * Show the form for creating a new resource. 26 */ 27 public function create() 28 { 29 // 30 } 31 32 /** 33 * Store a newly created resource in storage. 34 */ 35 public function store(Request $request) 36 { 37 // 38 } 39 40 /** 41 * Display the specified resource. 42 */ 43 public function show(Workplace $workplace) 44 { 45 // 46 } 47 48 /** 49 * Show the form for editing the specified resource. 50 */ 51 public function edit(Workplace $workplace) 52 { 53 // 54 } 55 56 /** 57 * Update the specified resource in storage. 58 */ 59 public function update(Request $request, Workplace $workplace) 60 { 61 // 62 } 63 64 /** 65 * Remove the specified resource from storage. 66 */ 67 public function destroy(Workplace $workplace) 68 { 69 // 70 } 71}

register.blade.phpの一部

1<div class="mt-4"> 2 <x-input-label for="workplace_id" :value="__('workplace_id')" /> 3 <select class="form-control" id="workplace_id" name="workplace_id"> 4 @foreach ($workplaces as $workplace) 5 <option value="{{ $workplace->workplace->id }}">{{ $workplace->name }}</option> 6 @endforeach 7 </select> 8 <x-input-error :messages="$errors->get('workplace_id')" class="mt-2" /> 9 </div>

web.php

1<?php 2 3use App\Http\Controllers\ProfileController; 4use Illuminate\Support\Facades\Route; 5use App\Http\Controllers\WorkplaceController; 6 7/* 8|-------------------------------------------------------------------------- 9| Web Routes 10|-------------------------------------------------------------------------- 11| 12| Here is where you can register web routes for your application. These 13| routes are loaded by the RouteServiceProvider and all of them will 14| be assigned to the "web" middleware group. Make something great! 15| 16*/ 17 18// Route::get('/', function () { 19// return view('welcome'); 20// }); 21Route::get('/', function () { 22 return view('auth.login'); 23}); 24 25Route::get('/dashboard', function () { 26 return view('dashboard'); 27})->middleware(['auth', 'verified'])->name('dashboard'); 28 29Route::middleware('auth')->group(function () { 30 Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit'); 31 Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update'); 32 Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy'); 33}); 34 35require __DIR__.'/auth.php';

2024_02_14_125456_create_workplaces_table.php

1<?php 2 3use Illuminate\Database\Migrations\Migration; 4use Illuminate\Database\Schema\Blueprint; 5use Illuminate\Support\Facades\Schema; 6 7return new class extends Migration 8{ 9 /** 10 * Run the migrations. 11 */ 12 public function up(): void 13 { 14 Schema::create('workplaces', function (Blueprint $table) { 15 $table->id(); 16 $table->string('name'); 17 $table->timestamps(); 18 }); 19 } 20 21 /** 22 * Reverse the migrations. 23 */ 24 public function down(): void 25 { 26 Schema::dropIfExists('workplaces'); 27 } 28};

試したこと・調べたこと

  • teratailやGoogle等で検索した
  • ソースコードを自分なりに変更した
  • 知人に聞いた
  • その他
上記の詳細・結果

chatGptやいろいろなサイトで調べたので、ここで調べたと出せません。すいません。

補足

一つ疑問があります。
Controllerに記述する際、Viewに返すと記載があるのですが、画面が登録、修正、削除とあった場合、それぞれにリストを変えすコードの記述が必要なのでしょうか?

AWS Lightsail上のLaravel10です。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答3

0

ルーティング情報に getWorkplaces メソッドを呼び出す記述がありませんので、このメソッドは呼び出されてないのかと思います。

routes/auth.php の方に記述があると思いますが、 GET /register に対応するコントローラは
RegisteredUserControllerのcreateメソッドであり、この内容を修正する必要があるはずです。

コントローラが修正されずにViewに変数だけ増やしてしまっているので未定義の状態になっています。

投稿2024/02/18 07:46

Eggpan

総合スコア3036

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

自己解決

適切なコントローラーに
public function create(): View
{
$workplaces = Workplace::select('id', 'name')->get();
return view('auth.register', compact('workplaces'));
}
を追加したところ、うまくいきました。
ただ、文字化けしてしまうので問題解決に至っていません。
また別の質問にしようかと思うので、この質問はクローズいたします。

投稿2024/02/19 01:50

ratezou

総合スコア67

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

0

return view('profile.edit', compact('workplaces'));

となっているのに、viewのファイル名がregister.blade.phpとなっているのが気になります。「Undefined variable $workplaces」の原因はこれな気がします。何が正しいかは第三者には分かりませんが、この辺をご確認いただくのが良いのではないかと思います。

投稿2024/02/16 01:50

AbeTakashi

総合スコア4723

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

ratezou

2024/02/16 01:57

return view('register.blade', compact('workplaces')); return view('register', compact('workplaces')); 共に試してみましたが、エラーに変化ありませんでした。
AbeTakashi

2024/02/16 02:13 編集

そもそもUndefined variable $workplacesはどのファイルの何行目で発生しているのでしょうか? その情報を元にたどり着けませんかね? コントローラーから$workplacesを渡しているようには見えるので、あとはコントローラーとビューのファイルが正しくひも付けされてないだけのように見えます。 追記) エラーメッセージが変わらないということであれば、そもそもルーティング周りが間違ってる可能性が高いかもですね。URLが間違っている、web.phpの内容が間違っている可能性がありそうです。今一度、そちらも確認お願いします。どういうURLを叩いてるかが分からないので、第三者には分からないです。
ratezou

2024/02/16 04:18

エラーは、 @foreach ($workplaces as $workplace) この箇所で出ています。 URLは、 https://(ドメイン名).net/register です。 selectタグを止めてtextにすると普通に開きます。 https://www.youtube.com/watch?v=kfvLppwhmgQ これでできそうだと思ったのですが、5:26あたりの、timezone_identifiers_listの意味が分からず、途方にくれています。 ただ、このcontrollerを、 public function create(): View { $workplaces = Workplace::all(); dd($workplaces); return view('auth.register'); } としたところ、 Illuminate\Database\Eloquent\Collection {#1285 ▼ // app/Http/Controllers/Auth/RegisteredUserController.php:25 #items: array:1 [▼ 0 => App\Models \ Workplace {#1235 ▼ #connection: "mysql" #table: "workplaces" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] +preventsLazyLoading: false #perPage: 15 +exists: true +wasRecentlyCreated: false #escapeWhenCastingToString: false #attributes: array:4 [▼ "id" => 1 "name" => "いしかわ" "created_at" => null "updated_at" => null ] #original: array:4 [▶] #changes: [] #casts: [] #classCastCache: [] #attributeCastCache: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: [] #touches: [] +timestamps: true +usesUniqueIds: false #hidden: [] #visible: [] #fillable: array:1 [▶] #guarded: array:1 [▶] } ] #escapeWhenCastingToString: false } となりました。 timezone_identifiers_listを無視して::allで突き進めば視界が開けるのでしょうか・・・?
ratezou

2024/02/16 04:35 編集

ちなみに、WorkplaceControllerを public function getWorkplaces() { $workplaces = Workplace::all(); dd($workplaces); return view('auth.register', compact('workplaces')); } としてもなにも表示されませんでした。(Undefined variable $workplacesのままでした) routeに/registerも無いですし・・・。 あと、上記の通りしたとして、例えばドロップダウンを2つにしたい場合、returnはどう書くのかも疑問です。
AbeTakashi

2024/02/16 10:02

見た感じコレクションのデータが正しく$workplacesに入ってるようなので、return view('register', compact('workplaces')); とすればview側のregister.blade.phpで$workplacesが参照できるはずです。それができないということは、別のコントローラーかメソッドを経由してregister.blade.phpが呼び出されている、全く別のviewが呼ばれている、などの可能性などが考えられると思います。動画の部分は今回のエラーとあまり関係なさそうですし無視して良さそうですが。xdebugとか使って変数をモニタリングしながらステップ実行してみるとかしてみるといいかもですね。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.41%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問