Joel
Joel

Reputation: 3176

How to access my model in laravel?

I can't seem to figure out what's wrong with this code. I'm running laravel 5.4.

The error: https://www.dropbox.com/s/64ioxdf4mv6ps1w/Screenshot%202017-02-28%2020.11.33.png?dl=0

The Controller function:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Thread;


class ThreadController extends Controller
{

    public function show($id) {

        return Thread::where('id', '=', $id)->messages();
    }
}

The Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Thread extends Model
{
    public function messages()  
    {
        return $this->hasMany(Message::class)->get();
    }


}

Upvotes: 1

Views: 202

Answers (2)

redcenter
redcenter

Reputation: 836

Regarding Joel's question in the comments...

User::find(1)->messages->create($request->only('body'));

Is not calling the 'messages function' you mentioned and not returning the relationship. Instead, it is calling the messages property, which is something different.

Upvotes: 1

camelCase
camelCase

Reputation: 5598

I suggest adding your error code instead of linking to image (right now AWS is down, thus I'm unable to view the image).

Regardless, the messages method is defining a relationship and as such, is an instance of the query builder. Rather than chaining the get method there, I suggest a slightly different approach:

In your controller

public function show($id)
{
    // Use first() instead of get() since you're returning a
    // specific model by its primary key (I assume)
    return Thread::where('id', $id)->with('messages')->first();
}

And in your model

public function messages()
{
    // This returns a query builder instance, which is what you want.
    // It defines the relationship between Thread and Message
    return $this->hasMany(Message::class);
}

This will eager load your messages along with your Thread model.

Hope it helps!

Upvotes: 3

Related Questions