0

I am using axios in vue in laravel to post a method. And i am receiving the below error:

enter image description here

CommentController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Comment;
use Auth;

class CommentController extends Controller {
    public function index(Post $post){
        return response()->json($post->comments()->with('user')->latest()->get()); //latest is used to sort them(the latest one in the tops)
    }

    public function store(Request $request, Post $post){
        $comment = $post->comments()->create([
            'body' => $request->body,
            'user_id' => Auth::id() //Auth::id();
        ]);
        $comment = Comment::where('id', $comment->id)->with('user')->first();
        return $comment->toJson();
    }
}

Vue.js:

<script>
    const app = new Vue({
      el: '#app',
      data: {
          comments: {},
          commentBox: '',
          post: {!! $post->toJson() !!},
          user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!}
      },
      created: function() {
        this.getComments();
      },
      methods: {
        getComments: function(){
          axios.get(`/api/posts/${this.post.id}/comments`)
            .then(res => {
              this.comments = res.data;
            });
        },
        postComment: function() {
          axios.post(`/api/posts/${this.post.id}/comment`,{
            body: this.commentBox,
            user_id: this.user.id
          })
            .then(response => {
              console.log(response);
              this.comments.unshift(response.data);
              this.commentBox = '';
            })
            .catch(error => {
              console.log(this.user);
              console.log(error.response);
            });
        }
      }
    });

   </script>

When i pass user_id in CommentController.php hard-coded like below, the error disappear and everything run successfully:

$comment = $post->comments()->create([
        'body' => $request->body,
        'user_id' => '4' //Auth::id();
    ]);

Comment Model:

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    protected $fillable = [
        'body', 'user_id'
    ];

    public function post(){
        return $this->belongsTo('App\Post');
    }

    public function user(){
        return $this->belongsTo('App\User');
    }
}

api.php routes:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('posts/{post}/comments','CommentController@index');
Route::post('posts/{post}/comment','CommentController@store');

Route::middleware('auth:api')->group(function () {

});

app/Middlware/Authentication.php

<?php

namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }
}

Anyone have any idea why Auth::id() in controller is not w?

iamzouz
  • 99
  • 1
  • 3
  • 11
  • the user have logined ? – TsaiKoga Apr 05 '20 at 00:33
  • Can you provide `dd(Auth::user());` before create? – mare96 Apr 05 '20 at 10:11
  • Double check if `Comment` model has `user_id` key in `$fillable` array which is mandatory for massive assignment that is used by `create` method. – Tpojka Apr 05 '20 at 13:09
  • @TsaiKoga yes the user is logged-in – iamzouz Apr 05 '20 at 14:28
  • @mare96 yes the user exist, when i dd(Auth::user()); i received the user data – iamzouz Apr 05 '20 at 14:32
  • @Tpojka first i forget to user_id to $fillable, but after i have added user_id and still receiving the same error – iamzouz Apr 05 '20 at 14:37
  • plz post your auth middleware's code. – TsaiKoga Apr 05 '20 at 14:38
  • when u create the comment with hard-coded 4, it can be inserted, means it can be fillable. However, if `Auth::user()->id`, return null.Maybe you are hiding the `id`. – TsaiKoga Apr 05 '20 at 14:48
  • Do you have `user()` method/relation in `Comment` model? – Tpojka Apr 05 '20 at 15:26
  • @TsaiKoga I posted auth middleware's code and routes/api.php – iamzouz Apr 05 '20 at 18:42
  • @Tpojka I posted Comment.php model – iamzouz Apr 05 '20 at 18:43
  • `'null' !== null` – Tpojka Apr 05 '20 at 21:07
  • plz put the route inside the middleware: `Route::middleware('auth:api')->group(function () {Route::post('posts/{post}/comment','CommentController@store');}) ` – TsaiKoga Apr 06 '20 at 02:24
  • @Tpojka what ? i didnt understand what you said ? – iamzouz Apr 06 '20 at 15:57
  • @TsaiKoga i know that i have to put post inside the Route::middleware, but inside it im receiving an error: 401 (Unauthorized). So first to solve my first problem(Auth::id) then i will see the 401 (Unauthorized) error. – iamzouz Apr 06 '20 at 16:01
  • `user: {!! Auth::check() ? Auth::user()->toJson() : 'null' !!}` <- this line could lead you to unexpected results and eventually be reason of issue you are getting. You should use `null` for `null` and not `'null'` because (as I already said) `null !== 'null'`. `null` is `null` and `'null'` is non empty string. `is_null('null') === false` – Tpojka Apr 06 '20 at 16:01
  • @Tpojka ohh yeah i fix it to null, but that's not the problem, anw thank you – iamzouz Apr 07 '20 at 15:25

2 Answers2

1

sry i wrote wrong answer, because i could not write comment

you using wrong class. try import this

use Illuminate\Support\Facades\Auth;
  • @JosephNehme did you read this? see >> https://stackoverflow.com/q/52055866/13198697 –  Apr 05 '20 at 00:39
0

Try this:

$user = Auth::user();

$comment = $post->comments()->create([
    'body' => $request->body,
    'user_id' => $user->id
]);
mchljams
  • 441
  • 2
  • 9