使用 laravel 5 和 Auth 更新登录的用户帐户设置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28999066/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Update logged in user account settings with laravel 5 and Auth
提问by Ronnie
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)
到目前为止,我是 laravel(实际上是任何 PHP 框架)的新手,但对 PHP 并不陌生。我创建了我的第一个项目并设法使用预建Auth
系统登录。我创建了一个新的路由、控制器和模型,AccountSettings
所以当我去/account
它时,它预先填充了登录用户的帐户信息(姓名和电子邮件)
Route::get('account', 'AccountSettingsController@index');
Route::post('account', 'AccountSettingsController@updateAccount');
When I hit the submit button on the form, I can see the form data I am POSTing (name, email and _token);
当我点击表单上的提交按钮时,我可以看到我正在发布的表单数据(姓名、电子邮件和 _token);
My AccountSettingsController
is:
我的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');
}
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.
但导致错误说User not found
。可以理解,因为它不在我use
的顶部。我试过了,use User
但这没有用。
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?
另一件事,这种类型的东西应该在模型中处理,对吗?我几个小时以来一直试图弄清楚这一点,我搜索的任何内容都没有真正相关。有人可以指出我正确的方向吗?
回答by ceejayoz
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.
在 Laravel 5 中,您将需要use App\User;
文件的顶部,而不是use User;
(绝对不是use Users;
)。该User
模型是在App
命名空间。
Side note: this is unnecessary:
旁注:这是不必要的:
$id = Auth::user()->id;
$user = User::find($id);
Just do:
做就是了:
$user = Auth::user();
and get cleaner code and one fewer database query out of it.
并从中获得更清晰的代码和更少的数据库查询。