1

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


}
1
  • Please add your error message/code in the body of your question. Commented Feb 28, 2017 at 19:38

2 Answers 2

3

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!

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

2 Comments

So a follow up question if that's OK. $message = User::find(1)->messages->create($request->only('body')); gives me an error saying that create() does not exist. Any idea why? The User model has a messages function that returns a hasMany relationship...
@Joel You'll want to ask in a new question, as it's too much to answer here. The concept is this: don't chain the create method onto your query. You need to get the object using firstOrFail or similar, then you can use the messages() method to save a message.
1

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.

1 Comment

A, true! But changing to messages() generates this error instead: BadMethodCallException in Macroable.php line 74: Method create does not exist.

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.