Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

chrisml's avatar

Get column value for a row from another table using id

I have a tasks table and a statuses table. The task table contains columns like id, name and status_id. I have seeded the statuses table with three rows: id: 1, name: open, id: 2, name: resolved and id: 3, name: closed. On the index action of my TaskController, I am outputting the tasks. I want to be able to get the name of the status, not just the status_id but I'm not sure what relationship I should use, as there is only three rows in the table. Or am I approaching this wrong?

0 likes
7 replies
bencarter78@hotmail.com's avatar

I think you'll want something like

class Task extends Model
{
    public function status()
    {
        return $this->hasOne(Status::class);
    }
}

In your controller...

public function index()
{
    return view('tasks.index', ['tasks' => Task::with('status')->get()]);
}

Then in your view...

@foreach($tasks as $task)
    <li>Task: {!! $task-name !!} Status: {!! $task->status->status_name !!}</li>
@endforeach

This should help http://laravel.com/docs/5.1/eloquent-relationships#one-to-one

chrisml's avatar

@bencarter78 - Am I right in saying that with a hasOne relationship, each task will have a row in the statuses table?

I added this to my Task model:

public function status()
    {
        return $this->hasOne('App\Status');
    }

But when I try App\Task::find(1)->status()->get(); I get an error:

BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::status()'

The way I imagined it would work is I have a status_id column on the tasks table. This references the id column on the statuses table. Which there will only ever have three rows (open, resolved, closed).

JarekTkaczyk's avatar

@cml123 It's belongsTo not hasOne:

public function status()
{
        return $this->belongsTo('App\Status');
}

However the error you're getting means, that the method was not found on the model - so check it first.

1 like
bencarter78@hotmail.com's avatar

Yes you're right.

If your status table looks like this...

id | name

1 | open

2 | resolved

3 | closed

Put simply all you need to do is...

$task = App\Task::find(1);

// To access the status
$task->status->name

That's it.

JarekTkaczyk's avatar
Level 53

@cml123 a typo somewhere then? PHP doesn't complain about missing methods unless they are... missing ;)

You can run composer dump-autoload -o as well, but it shouldn't be necessary.

Please or to participate in this conversation.