将模型属性分别传递给视图

问题描述 投票:3回答:2

我在将模型传递到相应视图时遇到了一些麻烦。我试图只有一个视图来创建和编辑我的模型。我也在使用验证。

我似乎无法找出一种优雅的方式将所有模型属性作为单独的变量传递给我的视图。

这是我的观点:

<div class="col-md-6 mb-3">
    <label for="title">Title</label>
    <input type="text" class="form-control" id="title" name="title" value="{{ old('title') }}">
</div>

我需要传递一个名为title的变量。但如果我要自己指定每一处房产,那就太荒谬了。

$product = Product::find($id);

return view('admin.products.new',
    ['id' => $id, 'title' => $product['title']]
); // this is stupid

我可以将模型作为一个整体传递给视图,但是我必须更改视图以检查变量是否已设置,然后从中获取嵌套的子值。这会破坏验证。

$product = Product::find($id);

return view('admin.products.new',
    ['product' => $product]
); // this is stupid

并在视图中:

<div class="col-md-6 mb-3">
    <label for="title">Title</label>
    <input type="text" class="form-control" id="title" name="title" value="{{ $product['title'] ?? '' }}">
</div>

我该怎么办?

php laravel
2个回答
1
投票

这是我认为你正在寻找的东西

/** @var Product $product */
$product = Product::find($id);

foreach($product->getAttributes() as $attribute=>$value)
   View::share($attribute,$value??"");

return view('admin.products.new');

0
投票

您可以创建名为ProductTrait的特征。 同时指定要检索的列。对于这个例子,我正在使用id和职称。

public function getProducts()
{
    $array = Product::all()->pluck('job_title', 'id')->toArray();
    return $array;
}

然后在你的控制器中:

$product_info = $this->getProducts();
return view('admin.products.new')->with('product_info',$product_info);

注意:不要忘记包含“使用App \ Traits \ ProductTrait;”在标题中也是 “使用ProductTrait;”在你的控制器内

输出: Image Here

© www.soinside.com 2019 - 2024. All rights reserved.