Aogiri14
Aogiri14

Reputation: 65

How to pass Auth::id() to the controller in laravel?

I have a payments controller but when I do dd of the authenticated user, it returns null.

namespace App\Http\Controllers\Api;

use App\Casefile;
use App\Http\Controllers\Controller;
use App\Payment;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class PaymentController extends Controller
{
    public function apiPaymentByUserId(Request $request) {
        $date_from = $request->$date_from;
        $date_to = $request->$date_to;

        $idAuthenticated = Auth::id();

        DB::connection()->enableQueryLog();

        $payments = DB::table("payments")
                        ->join('casefiles', 'casefiles.id','=', 'payments.casefile_id')
                        ->join('users', 'users.id', '=', 'casefiles.user_id')
                        ->select("payments.*")
                        ->where("payments.created_at", ">=", $date_from)
                        ->where("payments.created_at", "<=", $date_to)
                        ->where("casefiles.user_id", "=", $idAuthenticated)
                        ->get();

        // @dd(DB::getQueryLog());

        @dd($idAuthenticated);
     
        return response()->json([ 
            'success' => true, 
            'response' => $payments 
        ]);
    }
}

I need the auth id in the last where clause but it returns null.

What am I missing? Should I copy and paste more code to be more clearer? The route's action where I get parameters is POST.

Upvotes: 0

Views: 657

Answers (3)

Ruchika Kalal
Ruchika Kalal

Reputation: 59

You can get the id like this:

$idAuthenticated = Auth::user()->id;

Upvotes: 1

Jai Kumar
Jai Kumar

Reputation: 1

Yeah, you can get auth values like this:

$idAuthenticated = Auth::user()->id;
$username = Auth::user()->name;
$email = Auth::user()->email;

Or

$user = findOrFail(Auth::user()->id);

Upvotes: 0

weiwait
weiwait

Reputation: 1

That looks like an API request, if your default auth guard's config isn't API, you must assign the guard like: auth('api')->user()->id;.

Upvotes: 0

Related Questions