Laravel 5.2 - 创建帖子后登录用户

时间:2016-10-17 14:03:01

标签: php laravel laravel-5.2

我正在做一个所有用户都可以创建帖子和pubblic的项目! 如果用户未记录刀片,则启用包含电子邮件和密码的部分来创建帐户并发布。

enter image description here

我想做:

  1. 创建用户
  2. 在会话身份验证中记录用户(这是我的问题,我该怎么办?)
  3. 创建帖子(最后一点,因为我需要user_id)
  4. CONTROLLER

    // if user NOT registered my form will enable email and password field -- 
                if(!null($request->input('email') && request->input('password'))) {
                    // create user
    
                    $user = new User();
                    $user->name = $request->input('name');
                    $user->email = $request->input('email');
                    $user->password = bcrypt($request->input('name'));
                    $user->save();
    
                    // login user after create user
    
                    HOW CAN I LOG USER AFTER CREATED ACCOUNT ???
    
                    Thank you for your help!
    
                    // Get ID of user created
    
                    $get_user_id = User::where('email', '=', $request('email'))->first();
    
                    // create post
    
                    $post = new Post();
                    $post->title = $request->input('title'); 
                    $post->slug = str_slug($request->input('title'),'-'); 
                    $post->country = $request->input('country'); 
                    $post->zone = $request->input('zone');
                    $post->phone = $request->input('phone');
                    $post->address = $request->input('address');
                    $post->user_id = $get_user_id->id; 
                    $post->save(); 
                    return redirect('/')->with('message-success', 'Post creato con successo!');
    
                // IF USER LOGGED
    
                }else{
                    $post = new Post();
                    $post->title = $request->input('title'); 
                    $post->slug = str_slug($request->input('title'),'-'); 
                    $post->country = $request->input('country'); 
                    $post->zone = $request->input('zone');
                    $post->phone = $request->input('phone');
                    $post->address = $request->input('address');
                    $post->user_id = $request->input('user_id'); 
                    $post->save(); 
                    return redirect('/')->with('message-success', 'Post creato con successo!');
                }
    

3 个答案:

答案 0 :(得分:1)

答案 1 :(得分:1)

不清楚你想在这里做什么,获得用户ID的方式是不安全的。 我建议你使用$ user = Auth :: user();而是获取用户ID,($ user-> id)。

手动检查登录使用

if (Auth::attempt(['email' => $email, 'password' => $password])) {}

所以在你的例子中,我会做类似的事情:

    if (!Auth::attempt(['email' => $email, 'password' => $password])) {
       // create User
    } else {
       // $userId = Auth::user()->id;
    }

    // finally create post

答案 2 :(得分:0)

在您的类中添加__construct()方法,并添加以下代码:

public function __construct() {
    $this->middleware('auth', ['except' => ['index', 'show']]);
}

实际上必须有效