前提・実現したいこと
表題の通りです。
ビューで貸し出しテーブルにリレーションしたusersテーブルのnameとbooksテーブルのtitleを表示させたいです。そのうえで貸し出しテーブルのreturn_dateがnullの値を抽出したいです。
ですがリレーション先へのアクセスができなくて詰まっています。
発生している問題・エラーメッセージ
Trying to get property 'title' of non-object
dd(&datas)をしてみたところ
Illuminate\Database\Eloquent\Collection {#310 ▼ #items: array:1 [▼ 0 => App\Models\Lending {#312 ▼ #table: "lendings" #fillable: array:5 [▼ 0 => "user_id" 1 => "book_id" 2 => "lent_date" 3 => "return_date" 4 => "status" ] +timestamps: false #connection: "sqlite" #primaryKey: "id" #keyType: "int" +incrementing: true #with: [] #withCount: [] +preventsLazyLoading: false #perPage: 15 +exists: true +wasRecentlyCreated: false #attributes: array:6 [▼ "id" => "2" "user_id" => "2" "book_id" => "3" "lent_date" => "2021-6-30" "return_date" => null "status" => "0" ] #original: array:6 [▼ "id" => "2" "user_id" => "2" "book_id" => "3" "lent_date" => "2021-6-30" "return_date" => null "status" => "0" ] #changes: [] #casts: [] #classCastCache: [] #dates: [] #dateFormat: null #appends: [] #dispatchesEvents: [] #observables: [] #relations: [] #touches: [] #hidden: [] #visible: [] #guarded: array:1 [▼ 0 => "*" ] } ] }
該当のソースコード
###マイグレーションファイル
//database/migration/create_users_table <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
// database/migration/create_books_table <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateBooksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('books', function (Blueprint $table) { $table->increments('id'); $table->string('title'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('books'); } }
// database/migration/create_lendings_table <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateLendingsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('lendings', function (Blueprint $table) { $table->increments('id'); $table->integer('user_id'); $table->integer('book_id'); $table->timestamp('lent_date'); $table->timestamp('return_date')->nullable(); $table->boolean('status'); $table->foreign('user_id') ->references('id') ->on('users') ->onDelete('cascade'); $table->foreign('book_id') ->references('id') ->on('books') ->onDelete('cascade'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('lendings'); } }
モデル
// App/Model/Book <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\Lending; class Book extends Model { protected $table = 'books'; protected $fillable = ['title']; public $timestamps = false; public function lendings() { return $this->hasMany(Lending::class, 'book_id'); } public function getData() { $datas = [ 'id' => $this->id, 'title' => $this->title, ]; return $datas; } }
// App/Models/User <?php namespace App\Models; use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; use App\Models\Lending; class User extends Authenticatable { use HasFactory, Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public $timestamps = false; public function lendings() { return $this->hasMany(Lending::class); } }
// App/Models/Lending <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; use App\Models\User; use App\Models\Book; class Lending extends Model { protected $table = 'lendings'; protected $fillable = [ "user_id", 'book_id', 'lent_date', 'return_date', 'status', ]; public $timestamps = false; public function user() { return $this->belongsTo(User::class, 'id'); } public function book() { return $this->belongsTo(Book::class, 'id'); } public function getData() { $datas = [ 'id' => $this->id, 'user_id' => $this->user_id, 'book_id' => $this->book_id, 'lent_date' => $this->lent_date, 'return_date' => $this->status, ]; return $datas; } }
シーダー
// database/seeder/UserSeeder <?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Hash; class UserSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i = 1; $i <= 10; $i++) { DB::table('users')->insert([ 'id' => $i, 'name' => 'user' . $i, 'email' => 'email' . $i . '@gmail.com', 'password' => Hash::make('password'), ]); } } }
//database/seeder/BookSeeder <?php namespace Database\Seeders; use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; class BookSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { for ($i = 1; $i <= 10; $i++) { DB::table('books')->insert([ 'title' => 'title' . $i, ]); } } }
// database/seeder/LendingSeeder <?php namespace Database\Seeders; use Illuminate\Support\Facades\DB; use Illuminate\Database\Seeder; class LendingSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('lendings')->insert([ 'user_id' => '1', 'book_id' => '2', 'lent_date' => '2021-6-30', 'return_date' => '2021-7-4', 'status' => '0', ]); DB::table('lendings')->insert([ 'user_id' => '2', 'book_id' => '3', 'lent_date' => '2021-6-30', 'return_date' => null, 'status' => '0', ]); } }
コントローラ
// App/Http/Controller/LendingController <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Models\Lending; use App\Models\Book; class LendingController extends Controller { // 貸出中の本を表示 public function index() { $datas = Lending::whereNull('return_date')->get(); return view('index', ['datas' => $datas]); } }
ビュー
@extends('layouts.app') @section('content') @foreach($datas as $data) id{{ $data->id }} 本の名前{{ $data->books->title }} 借りての名前{{ $data->users->name }} 貸し出し日{{ $data->lent_date }} <br> @endforeach @endsection
補足情報(FW/ツールのバージョンなど)
Laravel 8.49.2
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。