使用laravel 5和Auth更新登录的用户帐户设置 [英] Update logged in user account settings with laravel 5 and Auth
问题描述
到目前为止,我对laravel(实际上是任何PHP框架)还是陌生的,但对PHP却并不陌生.我创建了第一个项目,并设法使用预构建的 Auth
系统登录.我创建了一个名为 AccountSettings
的新路由,控制器和模型,因此当我转到/account
时,它会预先填充已登录的用户帐户信息(名称和电子邮件)
I am new to laravel (any PHP framework actually) as of today but not new to PHP. I created my first project and managed to login using the prebuilt Auth
system. I created a new route, controller and model called AccountSettings
so when I go to /account
it's prepopulated with the logged in users account info (name and email)
Route::get('account', 'AccountSettingsController@index');
Route::post('account', 'AccountSettingsController@updateAccount');
当我点击表单上的提交"按钮时,我可以看到我正在发布的表单数据(名称,电子邮件和_token);
When I hit the submit button on the form, I can see the form data I am POSTing (name, email and _token);
我的 AccountSettingsController
是:
<?php namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\AccountSettings;
use Input;
use Request;
use Auth;
class AccountSettingsController extends Controller {
/**
* Display a listing of the resource.
*
* @return Response
*/
public function index()
{
return view('AccountSettings/index');
}
public function updateAccount()
{
var_dump(Input::all());
return view('AccountSettings/index');
}
}
我尝试通过以下方式保存用户信息:
I have tried saving the users info via:
public function updateAccount()
{
$id = Auth::user()->id;
$user = User::find($id);
$user->name = Request::input('name');
$user->email = Request::input('email');
$user->save();
return view('AccountSettings/index');
}
,但会显示一条错误消息,提示找不到用户
.可以理解,因为它不在我的 use
顶部.我试过 use User
,但这没用.
but results in an error saying User not found
. Understandable because It isn't in my use
's at the top. I tried use User
but that did not work.
另一件事,这种类型的东西应该在模型中处理,对吗?我已经尝试了好几个小时了,而我搜索的内容都没有任何实际意义.有人可以指出我正确的方向吗?
Another thing, this type of stuff should be handled in the model, correct? I have been trying to figure this out for hours now and anything I search isn't really related. Can someone point me in the right direction?
推荐答案
在Laravel 5中,您需要 use App \ User;
在文件顶部,而不是 use User;
(绝对不使用用户;
). User
模型位于 App
名称空间中.
In Laravel 5, you'll need use App\User;
up the top of the file, not use User;
(and definitely not use Users;
). The User
model is in the App
namespace.
旁注:这是不必要的:
$id = Auth::user()->id;
$user = User::find($id);
只需:
$user = Auth::user();
并获得更简洁的代码和更少的数据库查询.
and get cleaner code and one fewer database query out of it.
这篇关于使用laravel 5和Auth更新登录的用户帐户设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!