skip to Main Content

I have an app developed in flutter with a backend based on laravel.
It has databases in phpMyAdmin

I have the following code which retrieves, based on an API call from the app – a subset of category data based on user id.

public function get_categories()
    {
        $user_id = auth()->user()->id;
        $categories = Category::where('user_id', $user_id)->get();
        return $this->returnApiResponse(200, 'Categories fetched successfully', array('categories' => CategoryResource::collection($categories)));
    }

How do I adapt it so that it retrieves categories based on the matching user_id AND one that I specific e.g. user_id = 0

For example I have tried

$categories = Category::where('user_id', $user_id)->get() + Category::where('user_id', 0)->get();

and

$categories = Category::where('user_id', $user_id AND 0)->get()

But I am getting nowhere. I don’t really understand the php syntax and querying database tables.

I want it to return the categories associated with the user logged into the app, AND a user_id that I specify.

3

Answers


  1. You can add an additional "where" into your code:

    $categories = Category::where('user_id', $user_id)->where('category_name', 'something')->get()
    
    Login or Signup to reply.
  2. public function get_categories()
    {
        $userId = auth()->user()->id; //Get user id.
    
        // Query for categories matching the logged-in user OR user_id = 0
        $categories = Category::where('user_id', $userId)
                              ->orWhere('user_id', 0)
                              ->get();
    
        return $this->returnApiResponse(
            200,
            'Categories fetched successfully',
            array('categories' => CategoryResource::collection($categories))
        );
    }
    
    Login or Signup to reply.
  3. Please add second WHERE:

    $categories = Category::where('user_id', $user_id)
                          ->where('status', 1)
                          ->get();
    

    In this code we use this code ->where('status', 1) as second where please modify according to your code

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search