0

I have a giveaway table, it has a winner_id column in which the user ID on the site is entered. It is necessary that the ID from the winner_id column looks in the users table and displays the user login that has found on the site. How can this be done correctly?

1
  • Need more info - note (in detail) how to reproduce the problem. What you are looking for and why it is not what you expected. Commented Jan 21, 2020 at 22:46

1 Answer 1

2

You are looking for a One to Many (inversed) relationship from the "Giveway" model side. First, you need to create a "Giveaway" model which represents your "giveaway" database table, in case you don't have that already. You should have the "user" model, as this exists by default. Your "giveaway" model could look like this:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Giveaway extends Model
{
    /**
     * Get the user that is related to the giveaway.
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'id', 'winner_id');
    }
}

Now, get the giveaway instance and you can do something like this:

// this will print the user instance which is associated to the giveaway row with id #1
dd(Giveaway::find(1)->user);

For further details, please check the Laravel Docs: https://laravel.com/docs/6.x/eloquent-relationships#one-to-many-inverse

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.