Chris Chris - 1 month ago 7
PHP Question

Laravel ORM relationship method 'BelongsToMany' throwing error

Summary

I am receiving the following error when trying to call the relationship:


Object of class Illuminate\Database\Eloquent\Relations\BelongsToMany
could not be converted to string


My setup is very basic, and consists of two models,
User
and
Role
.

User Model [User.php]

<?php
use Illuminate\Auth\UserInterface;

class User extends Eloquent implements UserInterface {

protected $table = 'users';
protected $hidden = array('password');
protected $fillable = array('id', 'username', 'password');


public function getAuthIdentifier() {
return $this->getKey();
}

public function getAuthPassword() {
return $this->password;
}
}


Role Model [Role.php]

<?php
class Role extends Eloquent {

protected $table = "roles";
protected $fillable = array(
'id',
'code',
'name'
);

public function foo() {
return $this->belongsToMany('User', 'map_role_user', 'role_id', 'user_id');
}
}


And finally I'm calling the method
foo
in the routes file, example:

Route::get('role', function() {
return Role::find(1)->foo();
});

Answer

From

https://laravel.com/docs/5.3/eloquent-relationships or https://laravel.com/docs/4.2/eloquent#relationships

If a collection is cast to a string, it will be returned as JSON:

<?php
$roles = (string) User::find(1)->roles;