データをうまく渡せずに表示でエラーが起きました。

実現したいこと

子ネコでもデキル!初心者向け!Laravel9とCloud9で作る顧客管理システム(超長文) 2.0版 後編を参考に顧客の新規登録を行い、そのリストをviews/customers/index.htmlで表示させたいのですが、shopテーブルにある店舗名を表示させることが出来ません。

前提

顧客の新規登録は出来ました。
shopテーブルの中身にしっかりと店舗名が入っている事を確認しました。

mysql> SELECT * FROM shops; +----+-----------------+------------+------------+ | id | name | created_at | updated_at | +----+-----------------+------------+------------+ | 1 | 東京本店 | NULL | NULL | | 2 | 名古屋支店 | NULL | NULL | | 3 | 大阪支店 | NULL | NULL | +----+-----------------+------------+------------+ 3 rows in set (0.00 sec)

登録では1.2.3のどれかを記入し、店名を登録する形になっており、恐らく参考サイトではCustomer.controllerのindex内で登録されたcustomerテーブルを調べて、index.blade.phpの表示場所で登録した数字→店舗名のid→店舗名という流れで表示させたかったのですが、nullというエラーが表示されました。

発生している問題・エラーメッセージ

Attempt to read property "name" on null

該当のソースコード

views/customers/index.blade.php

1@extends('layouts.app') 2@section('content') 3 <div class="container"> 4 <div class="row justify-content-center"> 5 <div class="col-md-8"> 6 <div class="card"> 7 <div class="card-header">顧客</div> 8 <table width="100%" border="1"> 9 <thead> 10 <tr style="background-color: lightgray"> 11 <td>氏名</td> 12 <td>店舗</td> 13 <td>郵便番号</td> 14 <td>住所</td> 15 </tr> 16 </thead> 17 @foreach($customers as $customer) 18 <tr> 19 <td> 20 <a href="/customers/{{ $customer->id }}"> 21 {{ $customer->name }} 22 </a> 23 </td> 24 <td>{{ $customer->shop->name }}</td> ←エラー箇所 25 <td>{{ $customer->postal }}</td> 26 <td>{{ $customer->address }}</td> 27 </tr> 28 @endforeach 29 </table> 30 {{-- pagenation link ------------------------------------------------------------------------------- --}} 31 <table width="100%"> 32 <tr> 33 @if($customers->lastPage() > 1) 34 <td width="120px"><a href="{{ $customers->url(0) }}">最初のページへ</a></td> 35 <td width="120px"> 36 @if($customers->previousPageUrl()) 37 <a href="{{ $customers->previousPageUrl() }}">前のページへ</a> 38 @endif 39 </td> 40 <td width="120px" style="text-align: center">{{ $customers->currentPage() }} 41 / {{ $customers->lastPage() }}</td> 42 <td width="120px"> 43 @if($customers->nextPageUrl()) 44 <a href="{{ $customers->nextPageUrl() }}">次のページへ</a> 45 @endif 46 </td> 47 <td width="120px"><a href="{{ $customers->url($customers->lastPage()) }}">最後のページへ</a> 48 </td> 49 50 @endif 51 </tr> 52 </table> 53 {{-- End of pagenation link ------------------------------------------------------------------------- --}} 54 55 </div> 56 </div> 57 </div> 58 </div> 59@endsection

Controllers/CustomerController.php

1public function index() 2 { 3 $customers = Customer::where('shop_id', auth()->user()['shop_id'])->paginate(); 4 return view('customers.index', compact('customers')); 5 }

試したこと

CustomerControllerのindex内で店舗名を抜き出す処理を書くことも考えたのですが、うまくwhereなど、検索することが出来ませんでした。

補足情報(FW/ツールのバージョンなど)

PHP: PHP 8.1.21 (cli) (built: Jul 4 2023 23:26:29) (NTS gcc x86_64)
Laravel: Laravel Framework 9.52.11

コメントを投稿

0 コメント