Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mnd's avatar
Level 4

one route for both authenticated and guest users

Hi, I'm trying to use auth()->user() in controller but isn't giving any thing, when I added middleware('auth:api') to route it's work but I want to use only one route for both authenticated and guest users

0 likes
4 replies
bobbybouwmann's avatar

Well auth()->user() returns null when no user is logged in. Also, you can't access the current logged in user in the constructor of the controller.

Can you show your code?

mnd's avatar
Level 4

namespace App\Http\Resources\product;

use App\favorite; use Illuminate\Http\Resources\Json\JsonResource;

class filtterProductOptionsResource extends JsonResource {

public function toArray($request)
{



    $product = $this->product;

    $brand = $product->brand;

    $category = $product->category;

    $favorite = 0;

    if(Auth()->check()){
        $favorite = favorite::where('product_id', $product->id)->where('user_id', Auth()->user()->id)->count();
    }


    $media = $this->products_media;

    $discount = $product->discount;



    return [

        'id'         => $product->id,

        'name'       => request()->lang == 'ar'? $product->name_ar : $product->name_en,

        'brand'      => !empty($brand) > 0? $brand->name_en: '',
        
        'category'   => !empty($category) > 0? $category->name_en: '',
        
        'price'      => (number_format($this->price ?? 0,3)) ?? '--',

        'status'     => $this->status ?? "",
        
        'stockStatus'=> $product->product_option->sum('quantity') > 0 ? 1 : 0,
        
        'isFavorite' => $favorite ?? 0,
        
        'discount'   => $discount->count() > 0 ? $discount->last()->discount : 0,
        
        'image'      => isset($media->media_path)? url('/') . $media->first()->media_path : '' ?? '',
        
        
    ];
}

}

mnd's avatar
Level 4

I want to show user favorite products if he signed in otherwise not

walidabou's avatar

Auth is a facade, so you can't do Auth()->check() or Auth()->user().

Instead, you have to make it like this: Auth::check() or Auth::user().

Or with helper you can use auth()->user().

In other words you need to use :: with facades not ->

Please or to participate in this conversation.