Good morning
In my project, I do the default authentication provided by Laravel 5, hence it directs to my home normally when I log in. I know I logged in normally because when I put wrong data it returns error. At this time I try to get the user logged in $user = Auth::user();
and when I try to see if it returned the value I want it says it did not build the object: "Trying to get property of non-object".
To date, I've never worked with Laravel authentication. Can anyone help me?
Below the codes routes.php:
// Authentication routes...
Route::get('login', 'Auth\AuthController@getLogin');
Route::post('login', 'Auth\AuthController@postLogin');
Route::get('logout', 'Auth\AuthController@getLogout');
// Registration routes...
Route::get('register', 'Auth\AuthController@getRegister');
Route::post('register', 'Auth\AuthController@postRegister');
Route::get('/', 'PrincipalController@home');
Route::get('home', 'PrincipalController@home');
I did not switch to AuthController, except in redirectTo
, which I put to my home. The login and register did almost exactly as in the documentation, I just changed the style. I did not move in the Model User, I left exactly as the default
MainController.php:
use Auth;
use Redirect;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class PrincipalController extends Controller{
public function home(){
//Pode fazer um array de atributos/objetos e mandar pelo compact (pode separar os parâmetros no compact por vírgula)
$user = Auth::user();
if($user){
return view('home', compact('user'));
}else{
return view('auth/login');
}
}
}
AuthController.php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers;
protected $redirectTo = '/';
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
}