【问题标题】:Laravel: How to get data from View/Blade and pass to ControllerLaravel:如何从 View/Blade 获取数据并传递给控制器
【发布时间】:2021-01-07 23:35:16
【问题描述】:

表格:项目具有布尔值“onloan”

Patron(id, name), Item(id, name, onloan), Transactions (patron_id, item_id, loaned, due, returned)

关系:

赞助人.php

    public function transaction ()
    {
        return $this->hasMany(Transaction::class);
    }

项目.php

    public function transaction ()
    {
        return $this->hasMany(Transaction::class);
    }

Transaction.php

    public function item()
    {
        return $this->belongsTo(Item::class);
//        return $this->belongsTo('App\Item','item_id');
    }

    public function patron()
    {
        return $this->belongsTo(Patron::class);
    }

查看:create.blade.php

<label for="item_id">Item</label>
<select name="item_id" id="item_id" class="form-control select2">
  @foreach($items as $item)
    <option value="{{ $item->id }}">
      {{ $item->barcode }} - {{ $item->name }}
    </option>
  @endforeach
</select>

TransactionController.php

这部分是我遇到问题的地方,需要更新两 (2) 个表。

交易表:(这部分已经在工作了,没关系)
姓名……|项目…………|外借.....|到期..
约翰·多伊 |哈利波特 | 20 年 9 月 22 日 | 20 年 9 月 23 日

Items 表:(这部分我不知道如何在Controller中添加)
姓名…………|外借
哈利波特 | 1

• 如何更新此控制器中的外部表(项目)以便
$item->id 的“onloan”值为 1。

    public function store(TransactionRequest $request)
    {
        Transaction::create([
            'patron_id' => $request->patron_id,
            'item_id' => $request->item_id,
            'loaned' => $request->loaned,
            'due' => $request->due,
        ]);
        
        //This is what I tried, but it's not working.
        Item::find($request->item_id);
        $item->update([
            'onloan' => 1,
        ]);

请帮忙。谢谢。

【问题讨论】:

  • 输入的item_id不是那个值吗?
  • 啊。是的。我想你是正确的。让我检查一下。谢谢你。你说的对!让我修改一下我的问题。

标签: laravel view controller


【解决方案1】:

你可以这样写

Item::find($request->item_id)->update(['onloan' => 1,]);

创造你也可以做到

 Transaction::create([$request->all()]);

【讨论】:

  • 只传递 $request-&gt;all() 这是一个数组,不要将它包装在另一个数组中
猜你喜欢
  • 2021-08-19
  • 2021-12-26
  • 1970-01-01
  • 2016-11-25
  • 1970-01-01
  • 1970-01-01
  • 2021-06-29
  • 1970-01-01
  • 2019-11-01
相关资源
最近更新 更多