K3nzie K3nzie - 4 months ago 67
PHP Question

Laravel 5 eloquent relationship returns empty or null but the code seems ok

I did some searching but still I can't solve this, I'm coding a little library site for learning and I can't get relationships to work. (libro = book, autore = author, genere = genre)

In my tinker the command


returns null or empty, even if I call it as a method and use toArray

this is my code :

Libro model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Libro extends Model
protected $table = 'libri';
protected $fillable = ['titolo', 'id_autore', 'pubblicazione', 'trama', 'voto', 'image_url', 'id_genere'];
public function genere() {
return $this->belongsTo('App\Genere');

public function autore() {
return $this->belongsTo('App\Autore');

Autore Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Autore extends Model
protected $table = 'autori';
protected $fillable = ['nome', 'cognome', 'nascita', 'paese'];

public function libri() {
return $this->hasMany('App\Libro');
public function getFullNameAttribute()
return $this->nome . " " . $this->cognome;

The relation in my migration


I added the foreign keys in the mysql db, checked that on phpmyadmin, but still, it doesn't work, what am I doing wrong?

**adding more tinker responses to try outs **
If I try:

>>> App\Autore::find(2)->libri()->get()

I get:

Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'libri.autore_id' in 'where clause' (SQL: select * from `libri` where `libri`.`autore_id` = 2 and `libri`.`autore_id` is not null)'

If I try :


I get :

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






Your naming convention on the columns in your relation are incorrect (backwards). The convention is ${related_table}_id.

To solve this, alter your migration. Othwise, if you don't want to just adjust your migration, then specify the foreign key column in your Autore model as the 2nd argument to your hasMany relationship.

public function libri() {
    return $this->hasMany('App\Libro', 'id_autore')

And make sure to do the inverse for the Libro model.