2016-03-21 7 views
1

ここでは、新規に登録されたユーザーの内部ストアメソッドデータがデータベースに保存され、新しいユーザーがログインします。 showメソッドとshowメソッドの内側にdd(Auth :: user())がnull nullを返します。ルートミドルウェアグループにルートとコントローラがあります。これはユーザーがログインしていないことを意味します。 ユーザーがログインしていてもAuth :: user()はヌルを返します

public function store(Request $request) 
{ 
    // 
    $data = $request->all(); 
    print_r($data); 
    $rules = array(
     'username' => 'unique:users,username|required|alpha_num', 
     'password'=>'required|alpha_num', 
     'full_name'=>'required', 
     'email'=>'required|unique:users,email' 
    ); 

    // Create a new validator instance. 
    $validator = Validator::make($data, $rules); 
    if($validator->fails()){ 

     $errors=$validator->messages(); 
     return Redirect::route('user.create')->withErrors($validator); 

    }else{ 

     $user=new User(); 
     $user->username=$request->username; 
     $user->password=Hash::make($request->password); 
     $user->full_name=$request->full_name; 
     $user->email=$request->email; 
     $user->joined=date('d-m-y H-i-s'); 
     $user->save(); 


     if(Auth::attempt(['username'=>$request['username'],'password'=>$request['password']])){ 

      return redirect()->route('user.show',[$request['username']]); 
     } 
    } 

} 


public function show($user) 
{ 

    $indicator=is_numeric($user)?'user_id':'username'; 
    $info=User::where($indicator,'=',$user)->get()->first(); 
    if($info){ 

     dd(Auth::user()); // returns null 
     $data=array('info'=>$info); 
     return View::make('user.show')->with('info',$data); 
    }else{ 
     echo "this user doesn't exist"; 

     $info=User::where($indicator,'=', Auth::user()->$indicator)->first(); 
     $data=array('info'=>$info); 
     return View::make('user.show')->with('info',$data); 
    } 
} 

私のユーザモデル:

namespace App; 

use Illuminate\Database\Eloquent\Model; 
use Illuminate\Contracts\Auth\Authenticatable; 
class User extends Model implements Authenticatable 
{ 

    use \Illuminate\Auth\Authenticatable; 
    protected $table = 'users'; 
    public $timestamps = false; 


} 
+0

デフォルト認証を使用しているか、手動で編集しましたか? – Hamelraj

+0

私の質問に私のユーザーモデルを追加しました..plz check..thats私はどのように認証を使用しています...何も手作業なし –

+0

laravel 5.2を使用する場合は、ルートall urlにweb guard groupを設定する必要があります。セッションミドルウェアは "Web"ミドルウェアであるため。 –

答えて

1

お店の関数の最後のif前と$ユーザを保存した後は、今Auth::user()が常に返されますAuth::login($user);

 $user->save(); 

    Auth::login($user); 

//In case of adding a new user, Even the below If is not necessary 
    if(Auth::attempt(['username'=>$request['username'],'password'=>$request['password' ]])){ 


     return redirect()->route('user.show',[$request['username']]); 
    } 

を追加$user

+0

auth :: attempt..doesn't auth ::ユーザーが自動的にログインしないで、auth login後にauth loginを使用する必要があるのはなぜですか? –

+1

@ AL-zami私は自分の答えを編集しました。あなたがしたことはちょっと奇妙です! DBに新しいものを追加したら、Auth :: attempt()をチェックする必要はありません! Auth ::試行は、ユーザーにサインインしないログインに使用されます。ので、保存した後はAuth :: login($ user);大丈夫でしょう –

+0

十分にいいです:)ありがとう –

関連する問題