LARAVEL:显示属于特定 user_id 的列表

LARAVEL: Display lists that belongs to a specific user_id

我正在为一个网站创建一个克隆,parents 可以在该网站上创建他们刚出生的婴儿所需物品的清单,以便其他人可以将其作为礼物送给他们。

此时我已经设法将数据插入到我的 table 中,并将该行数据 link 插入到用户 ID(即已登录并完成表单的用户)中。 我已经设法显示所有用户 ID 的所有列表,但是当我转到经过身份验证的用户的仪表板时,我只想显示 linked 到他的 user_id 的列表。 我无法让它工作,但我确定我必须使用 hasMany() 和 belongsTo()。 这是我的代码:

我的迁移:

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique;
            $table->binary('password');
            $table->enum('role', ['user','admin'])->default('user');
            $table->timestamp('created_at');
            $table->timestamp('updated_at');
        });

        Schema::create('lists', function (Blueprint $table)
        {
            $table->increments('id');
            $table->foreignId('user_id')->nullable()->constrained()->onDelete('cascade');
            $table->string('baby');
            $table->string('vader');
            $table->string('moeder');
            $table->integer('telefoonnummer');
            $table->string('email');
            $table->string('adres');
            $table->integer('huisnummer');
            $table->string('toevoeging')->nullable();
            $table->string('stad');
            $table->integer('postcode');
            $table->string('land');
        });
    }

我的用户模型:

class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function birthLists()
    {
        return $this->hasMany(Birthlist::class, 'user_id');
    }
}

我的 Birthlist 模型:

class Birthlist extends Model
{
    use HasFactory;

    protected  $table = 'lists';

    protected $primaryKey = 'id';

    protected $fillable = 
    [
        'user_id',
        'baby',
        'vader',
        'moeder',
        'telefoonnummer',
        'email',
        'adres',
        'huisnummer',
        'toevoeging',
        'stad',
        'postcode',
        'land'
    ];

    public $timestamps = false;

    public function user()
    {
        return $this->belongsTo(User::class, 'user_id');
    }
}

我的控制器

<?php 

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Providers\RouteServiceProvider;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use App\Models\User;
use App\Models\Birthlist;



class DashController extends Controller 
{

    public function dashboard($id) 
    {
        $userId = Auth::id();
        $lists = Birthlist::where('user_id')->first();

        return view('dashboard', [
            'lists' => $lists,

        ]);
    }

}

我的观点

<body class="bg-red-100 w-screen h-screen pb">
        <main class="">
            <div class="text-center p-8 bg-green-100">
                <p class="">welkom</p>
                <h2 class="text-3xl font-bold">{{ Auth::user()->name }}</h2>
            </div>
            <section class="bg-red-100">
                <span class="p-4"><p class="text-center text-xl font-semibold">Mijn lijsten</p></span>
                    @foreach ($lists->birthLists as $list)
                        <div class="bg-red-200 p-8 bg-gradient-to-b from-green-300 to-fuchsia-400 drop-shadow-xl text-white md:w-5/12 xl:w-3/12">
                            <div class="text-3xl font-bold">
                                {{ $list->baby }}
                            </div>
                            <div class="flex flex-row justify-between">
                                {{ $list->vader }} & {{ $list->moeder }}
                            </div>
                        </div>
                    @endforeach
            </section>
        </main>
    @include('partials.footer')
</body>

在用户模型中:

public function birthLists()
{
   return $this->hasMany(Birthlist::class);
}

并且在视图中:


<body class="bg-red-100 w-screen h-screen pb">
        <main class="">
            <div class="text-center p-8 bg-green-100">
                <p class="">welkom</p>
                <h2 class="text-3xl font-bold">{{ Auth::user()->name }}</h2>
            </div>
            <section class="bg-red-100">
                <span class="p-4"><p class="text-center text-xl font-semibold">Mijn lijsten</p></span>
                    @foreach (auth()->user()->birthLists as $list)
                        <div class="bg-red-200 p-8 bg-gradient-to-b from-green-300 to-fuchsia-400 drop-shadow-xl text-white md:w-5/12 xl:w-3/12">
                            <div class="text-3xl font-bold">
                                {{ $list->baby }}
                            </div>
                            <div class="flex flex-row justify-between">
                                {{ $list->vader }} & {{ $list->moeder }}
                            </div>
                        </div>
                    @endforeach
            </section>
        </main>
    @include('partials.footer')
</body>

并且不需要从控制器获取数据,因为您可以在 blade 文件中获取 birthLists。