2017-09-04 110 views
0

A store has many products是關係。路徑模型綁定關係

如何創建新產品,保存store_id和其他產品詳細信息。

代碼如下。

路線是

Route::resource('stores.product', 'productcontroller'); 

即具有產品路線結合模型存儲。

型號Store

class store extends Model 
{ 
    public function product() 
    { 
     return $this->hasMany(product::class); 
    } 
} 

create product查看。

<form method="POST" action="/stores/{{$store->id}}/product" enctype="multipart/form-data"> 
    {{ csrf_field() }} 
    <div class="form-group"> 
     name <input type="text" name="name" /> 
    </div> 

[email protected]

public function store (store $store, Request $request) 
{ 
    $this->validate($request, [ 
     'name' => 'required|max:255', 
     'detail' => 'nullable' , 
    ]); 

    $product = new product; 
    $product-> user_id = auth()->id(); 
    $product-> store_id = $store->id; 
    $product-> name = $request->name; 
    $product->save(); 
    return redirect('/stores/{{$store->id}}/product'); 
} 

請解釋路徑模型,結合中關係的作品。

我應該創建表單的方法和操作?

[email protected]哪裏應該返回重定向?

回答

0

首先,你必須創建商店和產品 之間像這樣的反比關係:你有你所有的門店傳遞給你創造的產品頁面

class Store extends Model 
{ 
    public function products() 
    { 
     return $this->hasMany(Product::class); 
    } 
} 

class Product extends Model 
{ 
    public function store() 
    { 
     return $this->belonsTo(Store::class); 
    } 
} 

二:

public function create(){ 
    $storList = Store::all(); 
    return view("createproductview", compact("storList")); 
} 

在這種頁面,您必須顯示商店以選擇其中一個,並從驗證過程管理您的錯誤:

<form method="POST" action="{ route("product.store") }}" enctype="multipart/form-data"> 
    {{ csrf_field() }} 
    <div class="form-group {{ ($errors->has('store'))?"has-error":"" }}"> 
     <label for="store">Store</label> 
     <select class="form-control" name="tipoaudiencia" id="store"> 
      <option value="">Select one option</option> 
      @foreach($storList as $row) 
       <option {{ (old("store") == $row->id ? "selected":"") }} value="{{ $row->id }}">{{ $row->name }}</option> 
      @endforeach 
     </select> 
     @if($errors->has('store'))<p class="help-block">{{ $errors->first('store') }}</p>@endif 
    </div> 
    <div class="form-group required {{ ($errors->has('name'))?"has-error":"" }}"> 
     <label for="name">Name</label> 
     <input type="text" class="form-control" id="name" placeholder="name" name="name" value="{{ old('name') }}" autofocus> 
     @if($errors->has('name'))<p class="help-block">{{ $errors->first('name') }}</p>@endif 
    </div> 
    ... 
</form> 

和持續的存儲功能:

public function store (Request $request) 
{ 
    $this->validate($request, [ 
     'name' => 'required|max:255', 
     'store' => 'required' 
    ]); 

    $product = new Product; 
    $product->name = $request->name; 
    $store = Store::find($request->store); 
    $store->products()->save($product);//this saves the product and manage the relation. 
    return redirect('/stores/'.$store->id.'/'.$product->id); 
} 

希望這有助於你