Ronnie
Ronnie

Reputation: 11198

Update logged in user account settings with laravel 5 and Auth

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');

When I hit the submit button on the form, I can see the form data I am POSTing (name, email and _token);

My AccountSettingsController is:

<?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.

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?

Upvotes: 14

Views: 37608

Answers (1)

ceejayoz
ceejayoz

Reputation: 180024

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.

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.

Upvotes: 26

Related Questions