Chris Chris - 1 year ago 98
PHP Question

Laravel ORM relationship method 'BelongsToMany' throwing error


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 Model [User.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]

class Role extends Eloquent {

protected $table = "roles";
protected $fillable = array(

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

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

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

Answer Source

From or

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

$roles = (string) User::find(1)->roles;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download