Laravel 5.1 - Eloquent Relationships

I am new to Laravel. I was looking at the Eloquent relationships. I followed the documentation and defined my one to many relationship as:

// in the test model
 public function questions()
      return $this->hasMany('App\Question', 'test_name_id', 'test_id');
// in the question model
public function test()
      return $this->belongsTo('App\Test', 'test_name_id', 'test_id');

Note that i have not followed the convention for naming the id's. So if I do this in the Tinker:

$test = App\Test::first();
$question = $test->questions;

It works fine. But if want the record any other than first like doing:

$test = App\Test::where(['test_id'=>'2'])->get();
$question = $test->questions;

It gives me this error:

PHP error:  Trying to get property of non-object on line 1

Can any one please explain me what I am doing wrong here and how does this work properly?


Try ->first() instead of get(). get() returns array. Or use protected $primaryKey = 'test_id'; in test model and then ->find($id)

Need Your Help

rethinkdb eqJoin matching

javascript rethinkdb rethinkdb-javascript

Hi I'm using javascript with rethinkdb, and I'm trying to figure out how to use eqJoin when the id of the target is not on the maintable but on the second table.