Home > Blockchain >  LARAVEL: Display lists that belongs to a specific user_id
LARAVEL: Display lists that belongs to a specific user_id

Time:05-23

I'm creating a clone for a website where parents can create a list of things they need for their newborn baby so other people can buy it for them as a gift.

At this moment I've managed to insert data into my table and to link that row of data to the user id (so user who is logged in and completed the form). I've managed to show all the lists from all the user id's but when I go to the dashboard of the authenticated user, I only want to show the lists who is linked to his user_id. I can't get it working but I'm sure I have to use hasMany() and belongsTo(). This is my code:

My migration:

    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');
        });
    }

My User model:

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');
    }
}

My Birthlist model:

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');
    }
}

My controller

<?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,

        ]);
    }

}

My view

<body >
        <main >
            <div >
                <p >welkom</p>
                <h2 >{{ Auth::user()->name }}</h2>
            </div>
            <section >
                <span ><p >Mijn lijsten</p></span>
                    @foreach ($lists->birthLists as $list)
                        <div >
                            <div >
                                {{ $list->baby }}
                            </div>
                            <div >
                                {{ $list->vader }} & {{ $list->moeder }}
                            </div>
                        </div>
                    @endforeach
            </section>
        </main>
    @include('partials.footer')
</body>

CodePudding user response:

In User model :

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

and in view :


<body >
        <main >
            <div >
                <p >welkom</p>
                <h2 >{{ Auth::user()->name }}</h2>
            </div>
            <section >
                <span ><p >Mijn lijsten</p></span>
                    @foreach (auth()->user()->birthLists as $list)
                        <div >
                            <div >
                                {{ $list->baby }}
                            </div>
                            <div >
                                {{ $list->vader }} & {{ $list->moeder }}
                            </div>
                        </div>
                    @endforeach
            </section>
        </main>
    @include('partials.footer')
</body>

and don't need to get data from controller because you can get birthLists in blade file.

  • Related