LoginSignup
0
0

More than 1 year has passed since last update.

Laravel: Controllerのstoreメソッドの引数にはRequestをつけよう

Posted at

はじめに

Laravel6を用いて、商品のいいね機能を実装していました。
その際、1時間もつまづいたエラーがありました。

Too few arguments to function App\Http\Controllers\User\Product\RateController::store(), 1 passed in /var/www/ec_Laravel/vendor/laravel/framework/src/Illuminate/Routing/Controller.php on line 54 and exactly 2 expected

こちらは、「引数が足りていないよ」みたいな感じのエラーでした。

修正前コード

web.php
// 中略
Route::resource('user/product/{product_id}/rate', 'User\Product\RateController', ['only' => ['store', 'update', 'destroy']]);
show.blade.php
<form method="POST" action="{{ route('rate.store', $product->product_id)}}">
    @csrf
        <input type="hidden" name="rate_type" value="1">
        <button type="submit">提出</button>
</form>
RateContoroller.php
public function store($product_id, $request)
{
    // ここでエラーが発生


    Rate::create([
        'rate_type' => $request->rate_type,
        'user_id' => Auth::id(),
        'product_id' => $product_id,
    ]);
    
    return redirect()->back();
}

普通にproduct_idrequestをPOSTメソッドで渡しているんだが???

これで1時間ぐらい悩まされました。

解決方法

RateContoroller.php
use Illuminate\Http\Request;

public function store($product_id, Request $request)
{
    Rate::create([
        'rate_type' => $request->rate_type,
        'user_id' => Auth::id(),
        'product_id' => $product_id,
    ]);

    return redirect()->back();
}

なんとstoreメソッドの$requestの前にRequestをつければ解決できました。

公式ドキュメントをちゃんと読みましょう...

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0