Mohamed Ahmed
Mohamed Ahmed

Reputation: 35

Call to undefined method Illuminate\Database\Query\Builder::post()

I have a problem with using the query builders that give me the undefined method error for using post() in the routes file.

Usually I use the return of

User::find($id)->post; 

but when I call post as a function, it doesn't work and gives me:

Call to undefined method Illuminate\Database\Query\Builder::post()

User Model

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{


  protected $fillable = [
    'name', 'email', 'password',
 ];

 protected $hidden = [
     'password', 'remember_token',
 ];


 protected function post()
 {       
     return $this->hasOne('App\Post');  
 }

 }

Routes

  Route::get('/', function () {
  return view('welcome');
  });



  Route::get('/user/{id}/post',function($id){

  return User::find($id)->post()->get();    

  });

Upvotes: 3

Views: 3091

Answers (3)

Mathew Berry
Mathew Berry

Reputation: 148

The post() method in your User class needs to be public. Right now it's protected, which means outside classes can't access it. ~ @jackel414

As Jackel414 mentioned your post() function is protected and needs to be public for you to access it.

I noticed that you're running the get() function on a one to one relationship, this function is designed to bring back a collection of data unless you pass an id as the parameter, it's best practice to use the examples below:

return User::find($id)->post;

Or

return User::with('post')->find($id);

Alternatively you may bring back the builder to expand your queries even further.

return User::find($id)->post();

Upvotes: 2

jackel414
jackel414

Reputation: 1686

The post() method in your User class needs to be public. Right now it's protected, which means outside classes can't access it.

Upvotes: 3

bvelastegui
bvelastegui

Reputation: 61

try this:

Routes

Route::get('/user/{id}/post',function($id){

   return User::with('post')->find($id);    

});

Upvotes: 0

Related Questions