字段“ user_id”为空

时间:2019-07-14 20:14:06

标签: php database laravel

今天我已经建立了评论系统,但是还没有完成。在我的数据库中,所有字段都用日期填充,但是user_id还没有。如何保存在{{1 }},已验证用户的ID?这是我的代码。

CommentsController:

user_id

我的观点

public function store(Request $request, $post_id)
    {
        $this->validate($request, array(
            'username' => 'required|max:255',
            'mail' => 'required|mail|max:255',
            'comment' => 'required|min:5|max:2000',
        ));

        $post = Post::find($post_id);

        $comment = new Comment();
        $comment->username = $request->username;
        $comment->email = $request->email;
        $comment->comment = $request->comment;
        $comment->approved = true;
        $comment->post()->associate($post);

        $comment->save();

        Session::flash('message', "Message posted successfully!");
        return Redirect::back();
    }

我的路线

<div class="row">
  <div id="comment-form">
    {{ Form::open(['route' => ['comments.store', $post->id], 'method' => 'POST']) }}
    <div class="row">
      <div class="col-md-6">
         {{ Form::label('username', "Username:") }}
        {{ Form::text('username', null, ['class' => 'form-control']) }}
      </div>
      <div class="col-md-6">
         {{ Form::label('email', "Email:") }}
        {{ Form::text('email', null, ['class' => 'form-control']) }}
      </div>
      <div class="col-md-6">
         {{ Form::label('comment', "Comment:") }}
        {{ Form::text('comment', null, ['class' => 'form-control']) }}
      </div>
      {{ Form::submit('Add Comment', ['class' => 'btn btn-success btn-xs']) }}

    </div>
    {{ Form::close() }}

  </div>

我试图将Route::post('comments/{post_id}', ['uses' => 'CommentsController@store', 'as' => 'comments.store']); 放入表单中,但失败了...

1 个答案:

答案 0 :(得分:0)

对于获得身份验证的用户,您应该仅使用Auth门面。我在下面说明如何使用它。

use Illuminate\Support\Facades\Auth;
$user = Auth::user(); // Get the currently authenticated user...
$user_id = Auth::id(); // Get the currently authenticated user's ID...

因此,要保存与评论关联的用户,您有两个选择:

$user_id = Auth::id();
$comment->user_id = $user;
$comment->save();

$user = Auth::user();
$comment->user = $user;
$comment->save();

如果您对Laravel身份验证有更多疑问,请查看https://laravel.com/docs/5.8/authentication#retrieving-the-authenticated-user