我想在控制器中获得登录用户

时间:2019-07-11 13:51:17

标签: laravel vue.js controller single-page-application

我正在创建一个帖子,现在我想获得Authenticated用户,以便我可以填写author_id。但是当我使用

$request->user(); or Auth::user();

它返回null。

如何将数据从vuejs组件传递到Controller?

这是我的Vue组件

Form.vue

data() {
 return {
  form:{
    title: '',
    seo_title: '',
    excerpt: '',
    body: '',
    image: '',
    meta_description: '',
    meta_keywords: '',
    category_id: '',
    status: '',
    featured: ''
  }
 },
 methods: {
   save() {
     post(this.storeURL, form)
        .then((res) => {
          this.$router.push('Post created successfully')
        })
   }
 }
}

PostController.php

$filename = $this->getFileName($request->image);
$request->image->move(public_path('storage/posts/'), $filename);

$article = new Post($request->all());

$article->slug = str_slug($request->title, '-');
$article->image = $filename;

$request->user()->posts()->save($article);

return response()
   ->json([
     'saved' => true,
     'id' => $article->id,
     'message' => 'You have successfully posted an article!'
   ]);

1 个答案:

答案 0 :(得分:0)

如果通过身份验证的用户为null,则很可能您没有通过auth中间件传递此路由。在您的web.php(如果是api路由,则为api.php)中,请确保您正在使用的任何路由都在该中间件中。因此,例如,如果这是一个postCreate路由,则可能看起来像这样:

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

    Route::get('yourPostCreateRoute', 'YourPostController@index');
    // etc.
}