laravel 5.2 - Auth :: user() - >用户名为空

时间:2016-03-13 19:54:25

标签: php laravel laravel-5.2

如果我在Blade文件中使用Auth :: user() - >用户名,则laravel会返回一个空字符串,但会填写Auth :: user() - >电子邮件。我使用自己的AuthController,我的登录,注册和注销工作完美,但我无法获得用户名。

routes.php文件

<?php

Route::group(['middleware' => ['web']] , function () {
    Route::get('/', function () {
        return view('welcome');
    })->name('home');
});

Route::group(['middleware' => ['web','guest']], function () {
    Route::auth();

     #Sign up Routes
    Route::get('/signup', function () {
        return view('auth.signup');
    })->name('auth.signup');
    Route::post('/signup', 'AuthController@signup');

    #Sign in Routes
    Route::get('/signin', function () {
        return view('auth.signin');
    })->name('auth.signin');
    Route::post('/signin', 'AuthController@signin');
});

Route::group(['middleware' => ['web','auth']], function () {
    Route::auth();

    #Sign out Routes
    Route::get('/signout', 'AuthController@signout')->name('auth.signout');
});

我的自定义Auth Controller是:

<?php

namespace App\Http\Controllers;

use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;

class AuthController extends Controller
{

  public function signup(Request $request) {
    $this->validate($request, [
        'email' => 'required|unique:users|email|max:255',
        'username' => 'required|unique:users|alpha_dash|min:2|max:20',
        'password' => 'required|min:6'
    ]);

    User::create([
        'email' => $request->input('email'),
        'username' => $request->input('username'),
        'password' => bcrypt($request->input('password')),
    ]);

    return redirect()->route('home');
  }

  public function signin(Request $request) {
    $this->validate($request, [
        'email' => 'required',
        'password' => 'required'
    ]);

    if(!Auth::attempt($request->only(['email', 'password']), $request->has('remember'))) {
        return redirect()->back()->with('flash-message','We can not sign you in with this data!'); 
    }

    return redirect()->route('home');
  }

  public function signout() {
    Auth::logout();

    return redirect()->route('home');
  }
}

也许有人可以帮助我

注意: 我将用户名添加到填充数组下的User.php中。

2 个答案:

答案 0 :(得分:2)

您很可能在username模型的$fillable中遗失User

create方法仅接受来自$fillable

的字段

答案 1 :(得分:0)

请像这样编辑您的用户模型:

protected $fillable = [
       'email', 'username', 'password',
    ];

Create方法只插入$ fillable字段。