我定义了Model/User.php和Model/Cart.php之间的1-n关系,第一个是Model/User.php,第二个是Controller中的checkoutPost函数。
型号
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable implements MustVerifyEmail
{
use HasApiTokens, HasFactory, Notifiable;
protected $table = 'users';
protected $guards = 'users';
protected $fillable = [
'username',
'email',
'password',
'email_verified_at'
];
protected $hidden = [
'password',
'remember_token'
];
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
public function carts(){
return $this->hasMany(Cart::class,'users_id','id');
}
}
字符串
控制器
public function checkoutPost(Request $request){
$user = Auth::user();
$message = [
'required' => ':attribute không được bỏ trống',
'min' => ':attribute phải lớn hơn 4 kí tự', // this is my message but in different language, dont worry about it
];
$data = $request->validate([
'first_name'=>'required|min:3',
'last_name'=>'required',
'email'=>'required|email',
'phone'=>'required|min:9',
'address'=>'required',
'payment_method'=>'required',
], $message);
$data = $request->only('first_name','last_name','email','phone','address','payment_method');
$data['users_id'] = $user->id;
$order = Order::create($data);
$user->carts->each(function ($cart) use ($order) {
OrderDetail::create([
'order_id' => $order->id,
'product_id' => $cart->product_id,
'price' => $cart->price,
'quantity' => $cart->quantity
]);
$cart->delete();
});
return redirect()->route('order.checkout');
}
}
型
它导致这行$user->carts->each(function ($cart) use ($order)
中的错误
我正在我的电子商务项目中执行Checkout过程。代码对我来说似乎是正确的,但我一直收到错误消息。此外,数据库中确实存在购物车数据。
1条答案
按热度按时间b1payxdu1#
如果您在尝试访问该属性时出现错误,则听起来您根本没有使用Eloquent。您很可能使用了一个身份验证保护,该保护使用的是使用
database
驱动程序的用户提供程序,而不是eloquent
驱动程序,后者返回的GenericUser
对象不是Eloquent模型。Eloquent会为一个不存在的属性/关系/属性给给予一个
null
。GenericUser
有一个__get
方法,它直接试图访问一个名为attributes
的数组,如果键不存在,就会抛出这样的错误。字符串