Laravel:函数 0 传递的参数太少,预期为 1”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/54127138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: Too few arguments to function 0 passed and exactly 1 expected"
提问by Demeteor
I know this has been asked before. ive seen the questions and answers but cant find something that I can get help from.
我知道以前有人问过这个问题。我看过问题和答案,但找不到可以帮助我的东西。
I am trying to pass simple data into my database. so far so good. I believe my problem arises when I try to add the userID since it has to be pulled from Auth. so here is my controller code.
我正在尝试将简单数据传递到我的数据库中。到目前为止,一切都很好。我相信当我尝试添加用户 ID 时会出现我的问题,因为它必须从 Auth 中提取。所以这是我的控制器代码。
side node , userID is from a foreign table called users. and userID will be used as a foreign key. in the userstable its called "id"
侧节点,userID 来自名为 users 的外部表。和 userID 将用作外键。在用户表中称为“id”
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ShopController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('/shop/addShop');
}
protected function validator(array $data)
{
return Validator::make($data, [
'userid' => ['required', 'string', 'max:255'],
'shopname' => ['required', 'string', 'max:255'],
'address' => ['required', 'string', 'max:255'],
'postal' => ['required', 'string', 'max:255'],
'city' => ['required', 'string', 'max:255'],
'phone' => ['required', 'string', 'max:255'],
]);
}
/**
* Add Users shop after a validation check.
*
* @param array $data
* @return \App\
*/
protected function create(array $data)
{
$userId = Auth::id();
return User::create([
'userid'=> $data[$userId],
'shopname' => $data['shopname'],
'address' => $data['address'],
'postal' => $data['postal'],
'city' => $data['city'],
'phone' => $data['phone'],
]);
}
}
and right here you can see my route.
在这里你可以看到我的路线。
<?php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
Route::post('/addShop', 'ShopController@create')->name('addShop');
Route::get('/addShop', 'ShopController@index')->name('addShop');
回答by Petay87
Use Request
使用请求
Your create function is expecting an array. However, Laravel is passing a POST request. Therefore, use the Request class instead. Your code should read:
您的 create 函数需要一个数组。但是,Laravel 正在传递 POST 请求。因此,请改用 Request 类。你的代码应该是:
namespace App\Http\Controllers;
use User;
use Illuminate\Http\Request;
protected function create(Request $data)
{
$userId = Auth::id();
return User::create([
'userid'=> $data[$userId],
'shopname' => $data['shopname'],
'address' => $data['address'],
'postal' => $data['postal'],
'city' => $data['city'],
'phone' => $data['phone'],
]);
}