Migrations
php
1<?php
2
3use Illuminate\Database\Migrations\Migration;
4use Illuminate\Database\Schema\Blueprint;
5use Illuminate\Support\Facades\Schema;
6
7class CreateBooksTable extends Migration
8{
9 10 * Run the migrations.
11 *
1213
14 public function up()
15 {
16 Schema::create('books', function (Blueprint $table) {
17 $table->id();
18 $table->string('name');
19 $table->bigInteger('price');
20 $table->string('detail', 1000)->nullable();
21 $table->timestamps();
22 });
23 }
24
25 26 * Reverse the migrations.
27 *
2829
30 public function down()
31 {
32 Schema::dropIfExists('book');
33 }
34}
35
php
1<?php
3use Illuminate\Database\Migrations\Migration;
4use Illuminate\Database\Schema\Blueprint;
5use Illuminate\Support\Facades\Schema;
7class CreateBookUserTable extends Migration
8{
9 1213
14 public function up()
15 {
16 Schema::create('book_user', function (Blueprint $table) {
17 $table->id();
18 $table->unsignedBigInteger('user_id');
19 $table->unsignedBigInteger('book_id');
20 $table->timestamps();
22 $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
23 $table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
24 });
25 }
27 3031
32 public function down()
33 {
34 Schema::dropIfExists('book_user');
35 }
36}
Models
php
1<?php
2
3namespace App;
4
5use Illuminate\Database\Eloquent\Relations\BelongsToMany;
6use Illuminate\Foundation\Auth\User as Authenticatable;
7use Illuminate\Notifications\Notifiable;
8
9class User extends Authenticatable
10{
11 use Notifiable;
12
13 14 * The attributes that are mass assignable.
15 *
1617
18 protected $fillable = [
19 'name', 'email', 'password',
20 ];
21
22 23 * The attributes that should be hidden for arrays.
24 *
2526
27 protected $hidden = [
28 'password', 'remember_token',
29 ];
30
31 32 * The attributes that should be cast to native types.
33 *
3435
36 protected $casts = [
37 'email_verified_at' => 'datetime',
38 ];
39
40 4142
43 public function books(): BelongsToMany
44 {
45 return $this->belongsToMany(Book::class)
46 ->withTimestamps();
47 }
48}
49
php
1<?php
2
3namespace App;
4
5use Carbon\Traits\Timestamp;
6use Illuminate\Database\Eloquent\Model;
7use Illuminate\Database\Eloquent\Relations\BelongsToMany;
8
9class Book extends Model
10{
11 use Timestamp;
12
13 protected $fillable = [
14 'name',
15 'price',
16 'detail',
17 ];
18
19 2021
22 public function users(): BelongsToMany
23 {
24 return $this->belongsToMany(User::class)
25 ->withTimestamps();
26 }
27}
28
factories
php
1<?php
2
3
4
5use App\User;
6use Faker\Generator as Faker;
7use Illuminate\Support\Str;
8
9/*
10|--------------------------------------------------------------------------
11| Model Factories
12|--------------------------------------------------------------------------
13|
14| This directory should contain each of the model factory definitions for
15| your application. Factories provide a convenient way to generate new
16| model instances for testing / seeding your application's database.
17|
18*/
19
20$factory->define(User::class, function (Faker $faker) {
21 return [
22 'name' => $faker->name,
23 'email' => $faker->unique()->safeEmail,
24 'email_verified_at' => now(),
25 'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
26 'remember_token' => Str::random(10),
27 'created_at' => $faker->dateTime('-10 years'),
28 'updated_at' => $faker->dateTime('-10 years'),
29 ];
30});
php
1<?php
2
3
4
5use App\Book;
6use Faker\Generator as Faker;
7
8$factory->define(Book::class, function (Faker $faker) {
9 return [
10 'name' => $faker->word,
11 'price' => $faker->numberBetween(1000, 3000),
12 'detail'=>null,
13 'created_at' => $faker->dateTime('-10 years'),
14 'updated_at' => $faker->dateTime('-10 years'),
15 ];
16});
17
Seeder
php
1<?php
3use Illuminate\Database\Seeder;
5class UserSeeder extends Seeder
6{
7 1011
12 public function run()
13 {
14 factory(\App\User::class, 5)->create();
15 }
16}
php
1<?php
2
3use Illuminate\Database\Seeder;
4
5class BookSeeder extends Seeder
6{
7 8 * Run the database seeds.
9 *
1011
12 public function run()
13 {
14 factory(\App\Book::class, 100)->create()->each(function (\App\Book $book) {
15 $count = rand(0, \App\User::all()->count());
16 $user_ids = \App\User::query()->inRandomOrder()->take($count)->pluck('id');
17
18 for ($i = 0; $i < $count; $i++) {
19 $start = now()->subYears(rand(0, 10))->subDays(rand(0, 365));
20 $book->users()->attach($user_ids[$i], [
21 'created_at' => $start
22 ]);
23 }
24 });
25 }
26}
UserController
php
1<?php
3namespace App\Http\Controllers;
5use App\User;
6use Illuminate\View\View;
8class UserController extends Controller
9{
10 1314
15 public function index(): View
16 {
17 $users = User::with(['books' => function ($query) {
18 $query->whereDate('pivot_created_at', now());
19 }])->get();
20 return view('users.index', compact('users'));
21 }
22}
Blade
views/users/index.blade.php
php
1<!doctype html>
2<html lang="ja">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport"
6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
8 <title>Document</title>
9</head>
10<body>
11<div>
12 <table>
13 <thead>
14 <tr>
15 <th>ユーザーID</th>
16 <th>ユーザー名</th>
17 <th>メールアドレス</th>
18 <th>本日貸出した本</th>
19 <th>貸出日時</th>
20 </tr>
21 </thead>
22 <tbody>
23 @foreach ($users as $user)
24 <tr>
25 <td>{{ $user->id }}</td>
26 <td>{{ $user->name }}</td>
27 <td>{{ $user->email }}</td>
28 <td>{{ $user->books->first()->name }}</td>
29 <td>{{ $user->books->first()->pivot->created_at }}</td>
30 </tr>
31 @endforeach
32 </tbody>
33 </table>
34</div>
35</body>
36</html>