我正在使用以下代码
public function show()
{
$id = Auth::user()->id;
$usuario = User::find($id);
$mascotin = Mascota::all();
$mascota = Mascota::find($id);
$mascota->save();
$cant_mascota = Mascota::count();
$cant_pregunta = Pregunta::count();
return view('usuario.show',[
'usuario' => $usuario,
'mascotin' => $mascotin,
'mascota' => $mascota,
'cant_mascota' => $cant_mascota,
'cant_pregunta' => $cant_pregunta,
]);
}
它给了我这个错误
Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR).Call to a member function save() on null
用户模型
public function mascotas(){
return $this->hasMany('App\Mascota','user_id', 'id');
}
Mascota模型
public function usuario()
{
return $this->belongsTo('App\User', 'id','user_id');
}
路线
Route::get('/home', 'UserController@show')->name('home');
希望你们能为我提供帮助,我是laravel的新手,我希望经过1天的培训才能解决此问题
答案 0 :(得分:0)
$usuario = Auth::user();
$id = $usuario->id; // you already have user from Auth or Request, does not need to request database again
$mascotin = Mascota::all();
$mascota = $mascotin->find($id); // you can search in collection
//if you want to create Mascotin if it doesn't exists use Mascota::firstOrCreate(['id' => $id]);
if(!$mascota){
throw new \Exception('Mascota not found', 404); //if $mascota is mandatory
}
$mascota->save(); // this does not have place here unless you are changing $mascota before that
$cant_mascota = $mascotin->count();
$cant_pregunta = Pregunta::count();
此外,您应该将身份验证中间件添加到此路由。只有登录的用户才能看到它。 我不确定“ Mascota”是什么意思(共享代码时使用英语会很好),但是与用户具有相同的ID不好。更好地使用关系。