我知道这已经被问过了。香港专业教育学院看到的问题和答案,但找不到我可以得到帮助的东西。
我正在尝试将简单数据传递到数据库中。到目前为止,一切都很好。 我认为当我尝试添加userID时会出现问题,因为必须从Auth中提取该ID。这是我的控制器代码。
侧节点,userID来自称为用户的外部表。和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'],
]);
}
}
在这里您可以看到我的路线。
<?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');
答案 0 :(得分:4)
您的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'],
]);
}