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

tnayanam's avatar

Need help with Eloquent Query

I have three tables.

  1. User table

id:

name:

  1. Bookmark table

id:

name:

user_id:

category_id:

  1. Category table

id:

name:

There is one to many between User to Bookmark and one to many between category and Bookmark. I have one form where I can create a bookmark. Now while creating bookmark I have one drop down which shows all the "category" previously created by that user, so that user can select one of the category and put the bookmark into it. But I am not able to fetch the "category" related to a particular user.

I need help in my "create" function of BookmarkController.

if I do something like :

$categories = Category::lists('name_category','id');

    return view('bookmark.create', compact('categories'));

it shows all the category irrespective of who has logged in. But I want to see only the category created by that logged in user in the drop down.

Below is my model

User.php

    <?php

    namespace App;

    use App\Bookmark;

    use Illuminate\Foundation\Auth\User as Authenticatable;

    class User extends Authenticatable

        {
            protected $fillable = [
            'name', 'email', 'password',
        ];

            protected $hidden = [
        
    'password', 'remember_token',
    
    ];

        public function userbookmarks()

        {

            return $this->hasMany('App\Bookmark');
        
    }
 
    }

  1. Category.php
        <?php

        namespace App;

        use App\Bookmark;

        use Illuminate\Database\Eloquent\Model;

        class Category extends Model
        {
    
        protected $fillable = [
    
             'name_category',

                'description_category'

            ];

            
      public function categorybookmarks()
        
    {

            return $this->hasMany('App\Bookmark');
            }       
    }

Bookmark.php

    <?php

        namespace App;
    
    use App\Category;

    use App\User;

    use Illuminate\Database\Eloquent\Model;

    class Bookmark extends Model    
    {
    
        protected $fillable = [
    
        'name',

            'url',

            'description',
        
    'image_url'

        ];
        
public function categorybookmarks()

        {
            return $this->belongsTo('App\Category');
        }

        public function userbookmarks()
        {
         return $this->belongsTo('App\User');
        }
    }

BookmarkController.php

<?php

namespace App\Http\Controllers;

use App\Category;

use App\User;

use App\Bookmark;

use Illuminate\Http\Request;


use App\Http\Requests;

class BookmarkController extends Controller

{

  public function __construct(User $user)

{

        $this->middleware('auth');
   
 $this->user = $user;
    
}

    public function index()
    {
        // show all the categories for bookmarks
        return 'all categories';
    
}


public function create()

        {
        //1.  From the Bookmarks table I want to filter the record pertaining to the current logged in user
 and then check all the values present in the  corresponding "category_id" column, 
then fetch the category detail of these "Category_id" to populate my dropdown .
    }

}
0 likes
9 replies
goatshark's avatar

@tnayanam Looks like you just need to add a hasMany categories relationship to your User model, along with (if it's not there already) a user_id field on your categories table. If you're ever going to want to have a bookmark in multiple categories, you should look at using a pivot table between categories and bookmarks. https://laravel.com/docs/master/eloquent-relationships#many-to-many Or look into a "taggable" package like cartalyst/tags.

1 like
tnayanam's avatar

@goatshark : I already have added that. Kindly help me here. I just need to get the row pertaining to current logged in user so that I can fetch the category_id present in my bookmark table. Now with this category_id I can populate the dropdown of all the categories. please help.

tnayanam's avatar

I am just keeping 1-n relationship between categories and bookmark for now.

goatshark's avatar

@tnayanam Assuming your db tables are correct, then you should be able to get the list of all categories a user has created with this method on your User model:

public function categories()
{
    return $this->hasMany('App\Category');
}

So, when you have your user, as let's say $user, then $user->categories should return all categories belonging to that user.

Maybe I'm misinterpreting your question?

1 like
goatshark's avatar

Broadly: User hasMany App\Category

User hasMany App\Bookmark

Category belongsTo App\User

Category hasMany App\Bookmark

Bookmark belongsTo App\User

Bookmark belongsTo App\Category

1 like
tnayanam's avatar

@goatshark : I really apprecite your help here.

Can you provide me a solution where I can get all the category using the function called "userbookmarks" . I want to perform below steps.

  1. get curentloggein user
  2. call the userbookmarks function on it to get all the rows present in Bookmark table pertaining to that user.
  3. for all these rows go to the category_id column get that value.
  4. for all these category_id column fetch the category detail from category table.

Please help. I don't have any direct relation between user and category.

goatshark's avatar

Hey @tnayanam The short answer is to just build the relationship between User and Category. In the steps you propose, you won't get a list of every Category belonging to a User. You will at most only get a list of all categories that have been applied to bookmarks by that user. Also, without additional work (maybe using intersect on an array), you'll get duplicate categories in your list if more than one Bookmark is in the same category. Does that part make sense?

Without a relationship between user and category, the only way to walk toward something like this (that I know of) would be (assuming you're in your view and working with just the authenticated user)

@foreach (Auth::user()->userbookmarks as $bookmark)
    {{ $bookmark->category->name }}
@endforeach 

or something along those lines. I would build the relationship between user and category though.

1 like
tnayanam's avatar

@goatshark : I got you. So I am going to change the DB design now. So, now I have many to many between user and category where I have bookmark as the pivot (this relation already exists). Now again I will have one to many between user and category. So more like many to many and one to many both will exist between user and category. Am I making sense? I am new to all this. So kindly bear with me.

goatshark's avatar

@tnayanam manyToMany gets you into pivot tables. I updated one of my previous responses because it didn't format correctly the first time. Without using manyToMany/pivot table, that reply has the layout that I think you're looking for.

If you're jumping to a pivot table situation, in my opionin, your only pivot table would be bookmark_category. User will hasMany Bookmark and hasMany Category, then the pivot between Bookmark and Category.

Please or to participate in this conversation.