当我运行以下API时出现此错误
“间接修改重载属性App \ User :: $ attendance无效”。
我仍然无法弄清楚这么久。你能不能请别人帮助我。
public function apiPresent( $id, Request $request )
{
$tokenuser = User::with('attendance')
->where('token', $request->input('token'))->first();
$present = $request->input('present');
$user = User::with('attendance')->find($id);
if( $user && $tokenuser == $user )
{
$user->attendance->present = $present;
$user->attendance->date = Carbon::now()->format('d-m-Y');
$user->attendance->time = Carbon::now()->format('H-i');
$user->attendance->save();
return response()->json([
'status' => 'Ok',
'message' => 'Present Changed',
'Present' => $user->attendance->present
]);
}
else
{
return response()->json([
'status' => 'Fail',
'message' => 'Your state does not changed'
]);
}
}
答案 0 :(得分:1)
我认为问题在于您尝试直接分配App::User
的关系。您的代码段突出显示了这一点:
if( $user && $tokenuser->id == $user->id ){
$user->attendance->present = $present;
$user->attendance->date = Carbon::now()->format('d-m-Y');
$user->attendance->time = Carbon::now()->format('H-i');
$user->attendance->save();
...
在Eloquent中,您使用魔术__get()方法访问关系作为属性,该方法返回对象的副本。
当您尝试将任何值分配给任何关系的属性(在本例中为 $ user-> attendance )时,它不会对原始对象,因此警告。
您可以通过创建新对象实例并将其添加到create
方法来解决此问题,如下所示:
$attendance = new Attendance();
$attendance->present = $present;
$attendance->date = Carbon::now()->format('d-m-Y');
$attendance->time = Carbon::now()->format('H-i');
$user->attendance->create($attendance);
这将使用外键保存新记录。
答案 1 :(得分:0)
就我而言
Laravel php 5.7和Mysql 5.7 我为以下代码获取的错误是对重载属性Illuminate \ Http \ Request :: $ {
的间接修改错误代码
$config->name = $request->title;
$config->lead_by_id = $request->owner;
$config->tech_stack = $request->stack;
$config->is_POC = $request->
$config->updated_by = $request->
$config->start_date = $request->start_date;
$config->end_date = $request->end_date;
然后我发现我没有正确设置请求变量
修复
$config->name = $request->title;
$config->lead_by_id = $request->owner;
$config->tech_stack = $request->stack;
$config->is_POC = $request->poc;
$config->updated_by = $request->$user->id;
$config->start_date = $request->start_date;
$config->end_date = $request->end_date;
答案 2 :(得分:-2)
如果我理解你的问题。你正在节省出勤率。
试试这个:
use App\Attendance; // Add before controller declaration
public function apiPresent( $id, Request $request )
{
$tokenuser = User::where('token', $request->input('token'))->first();
$present = $request->input('present');
$user = User::find($id);
if( $user && $tokenuser->id == $user->id ){
$attendance = new Attendance;
$attendance->present = $present;
$attendance->date = Carbon::now()->format('d-m-Y');
$attendance->time = Carbon::now()->format('H-i');
$attendance->save();
return response()->json([
'status' => 'Ok',
'message' => 'Present Changed',
'Present' => $present
]);
}
else {
return response()->json([
'status' => 'Fail',
'message' => 'Your state does not changed'
]);
}
}
希望它有所帮助!