Search code examples
laraveljwttokenlaravel-8rest

How to access inputted token value - Laravel API


enter image description here

I am inputting a token as above and trying to print the token value with the below code. But getting error Undefined variable: token. I'm not sure whether i can access the token as below. Pls help me with ur suggestions.

<?php

namespace App\Http\Controllers;

use App\Models\Files;
use Illuminate\Support\Facades\Auth;

class FileController extends Controller
{
  public function upload()
    {
       $tock=Auth::user()->$token;
       dd($tock);
    }
}

Solution

  • You are trying to access the $token variable on the user, even though it does not exist.

    Instead you should by trying to access the request and the values that are send with the request. This can be achieved using the request() helper or by injecting the Request class into the function.

    With injection:

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Models\Files;
    use Illuminate\Http\Request; // Add request to namespace
    use Illuminate\Support\Facades\Auth;
    
    class FileController extends Controller
    {
      public function upload(Request $request)
        {
           dd($request->bearerToken());
        }
    }
    

    Or, without injection:

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Models\Files;
    use Illuminate\Support\Facades\Auth;
    
    class FileController extends Controller
    {
      public function upload()
        {
           dd($request->bearerToken());
        }
    }
    

    With the bearerToken() method you can access the Bearer token provided in the request.