2017-07-25 08:49
浏览 67

Laravel mutator或创建活动

I have two models, Card and Expense. Both have a type field. Whenever I add a new expense, I have a dropdown in the form to select a Card. They are related by a belongsTo relation.

The thing is, I want to automatically set the type field of my Expense to the same as my card's type. I do not want to have another dropdown for type in my expense form. Also, I want to keep using the following on my store method on my Expense Controller:


I think this should be possible by using a mutator perhaps in the model, but I'm not entirely sure how to approach this.

So in short, what I need is, when creating a new Expense, I need the type field to be grabbed from the related Card, and then inserted into the Expense type field.

What I don't want to do in my controller, is something like:

$expense = new Expense;
$expense->name = ... And so on
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duandanxiu6965 2017-07-25 08:54

    If you want to use type from the Card model, you could do something like this:

    $card = Card::find(1);
    $card->expenses()->create(array_merge($request->all(), ['type' => $card->type]));

    But it's not a good idea to duplicate type if you already have one in the Card model and Expense belongs to Card.

    点赞 打赏 评论

相关推荐 更多相似问题