Skip to content
Advertisement

Laravel 8: Call to a member function user() on array

I’m working with Laravel 8 to develop my forum project, and I wanted to add some like functionality to question that has been asked on forum by users.

So here is a form on question.blade.php:

<form action="{{ route('questions.likes', $show->id) }}" method="POST">
   @csrf
   <button class="btn">
      <i class="fas fa-thumbs-up"></i> <span>{{ $show->likes->count() }}</span>
   </button>
</form> 

And then at LikeController, I added this:

public function store(Question $id, Request $request)
    {
        $id->likes()->create([
            'user_id' => $_REQUEST->user()->id,
        ]);

        return back();
    }

But now I get this error:

Call to a member function user() on array 

Which is referring to this line:

'user_id' => $_REQUEST->user()->id,

So what is going wrong here? I need to pass the user id who pressed on like button in order to update likes table. How can I solve this issue?

I would really appreciate if you share any idea or suggestion about this with me…

Thanks in advance.

Advertisement

Answer

replace 'user_id' => $_REQUEST->user()->id;

with 'user_id' => $request->user();

edit : reason to the error

$_REQUEST is an associative array that by default contains the contents of $_GET, $_POST and $_COOKIE.this belongs to core PHP, not to the Laravel. that array doesn’t have connection with laravel user() object so that why the Call to a member function user() on array thrown.

$request is instance of lluminateHttpRequest this object have access to current authenticated user

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement