6

I'm having some trouble getting my Laravel relationships to work out. In my application, there is a one-to-many relationship between users and ideas. (A user may have multiple ideas.) I'm using Ardent.

Here's my User model:

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

use LaravelBook\Ardent\Ardent;

class User extends Ardent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = array('password', 'remember_token');
    protected $fillable = array('first_name', 'last_name', 'email', 'password');

    public $validation_errors;
    public $autoPurgeRedundantAttributes = true;
    public $autoHashPasswordAttributes = true;
    public $autoHydrateEntityFromInput = true;

    public static $passwordAttributes  = array('password');

    public static $rules = array(
        'first_name'            => 'required|between:1,16',
        'last_name'             => 'required|between:1,16',
        'email'                 => 'required|email|unique:users',
        'password'              => 'required|between:6,100'
    );

    public function ideas()
    {
        return $this->hasMany('Idea');
    }   
}

And here's my Idea model:

use LaravelBook\Ardent\Ardent;

class Idea extends Ardent {

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'ideas';

    protected $fillable = array('title');

    public $validation_errors;
    public $autoPurgeRedundantAttributes = true;
    public $autoHydrateEntityFromInput = true;

    public static $rules = array(
        'title'            => 'required'
    );

    public function user()
    {
        return $this->belongsTo('User');
    }
}

Finally, here's my controller code:

class IdeasController extends BaseController {

    public function postInsert()
    {
        $idea = new Idea;

        $idea->user()->associate(Auth::user());

        if($idea->save())
        {
            return Response::json(array(
                'success' => true,
                'idea_id' => $idea->id,
                'title' => $idea->title),
                200
            );
        }
        else
        {
            return Response::json(array(
                'success' => false,
                'errors' => json_encode($idea->errors)),
                400
            );
        }
    }

}

$idea->save() throws the error:

{
  "error": {
    "type": "LogicException",
    "message": "Relationship method must return an object of type Illuminate\\Database\\Eloquent\\Relations\\Relation",
    "file": "\/var\/www\/3os\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Eloquent\/Model.php",
    "line": 2498
  }
}

At first, I was trying to set the user_id in the Idea like so:

$idea->user_id = Auth::id();

I then changed it to:

$idea->user()->associate(Auth::user());

But the results were the same.

Any suggestions would be much appreciated.

2
  • What you want is you want to save many idea to a user? Commented Dec 30, 2014 at 19:23
  • In this specific case, I want to save one idea that is associated with a user. Commented Dec 30, 2014 at 19:30

2 Answers 2

4

You cannot use associate in that direction, since it can only be used on a belongsTo relationship. In your case, an idea belongs to a user and not the other way around.

I suspect there is an error when saving, as you create an idea without the required title, and you then try to get the errors by calling $idea->errors, while it should be $idea->errors().

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks lowerends. Auth::id() and Auth::user()->id seem to be the same thing. To verify, I printed them and both printed the same user id. Thanks for the tip about associate, but I'm still lost!
Brilliant! Sorry for the wild goose chase. You were absolutely correct.
0

associate will work on belognsTo relationship , in your cause what you have to use is Attaching A Related Model. See more about Attaching A Related Mode in documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.