vendredi 1 avril 2016

Is there a better way to assign an Eloquent relationship in Laravel using a Repository?

Assuming I have these 2 Models User and Account.
Where a User can have multiple Accounts. (hasMany)
And an Account belongs to a User. (belongsTo)

If I'm not using a Repository I would save the model and its relationship like this:

    $account = new Account();
    $account->username = $this->username;
    $account->secret = $this->secret;
    $account->user()->associate($this->user);
    $account->save();

And when using a Repository I see many people (and articles) doing it like this:

$accountRepository->create([
      'username' => $this->username,
      'secret'   => $this->secret,
      'user_id'  => $this->user()->id,
]);

My problem with this approach is in the user_id because it doesn't feel safe to manually assign this kind of relationship, additionally when someone else is reading this code he cannot tell what is the relation between the Account and User from there!!

The way I'm currently handling this is as follow: (it's kinda combination of the both ways)

    // create the account and attach the fields and the relationships
    $account = new Account();
    $account->username = $this->username;
    $account->secret = $this->secret;
    $account->user()->associate($this->user);

    // save the new created model with the repository
    $account = $accountRepository->create($account->toArray());

But I'm not really sure if there's any better way to do this!! All I need is to use the associate function because it feels safer and looks better for the readers. And to use a Repository to save and access my data.

Note: I am using the http://ift.tt/1BVSE6r to abstract the database layer.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire