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

danep's avatar
Level 1

Seeding Data to model that has globalscope with session on boot.

Hi Brainstrust, trying to create a seeder for a table that requires a session variable in the model's boot for a global scope, how do i initialise a session from the seeder. I have tried

request()->session()->regenerate(); and simply errors with 'Session store not set on request' Any ideas? Alternatively how do i override the boot function if request is not set? The models boot code is

static::addGlobalScope('client', function ($builder) { $builder->where('client_id', request()->session()->get('client_id')); });

Thanks in advance.

0 likes
5 replies
bobbybouwmann's avatar

Well the problem here is that a seeder is never going to be session aware. Also passing a session to a global scope is a really bad idea. You won't be able to perform queries using artisan as well. So if you would have a command that uses this global scope it would fail because the session will never be set!

As an alternative I would probably use a regular scope or use a different store. For example the cache or database driver.

danep's avatar
Level 1

I thought as much. :(

I am only passing a session variable, not the entire session. Reason I am trying to do it this way is i am trying to implement security for a customers table so that only users who are assigned to the client that the customer belongs to can see the customers (of the client). user and client is many to many via pivot, and customer is the model that has the globalscope set.

Any alternate ideas on how to achieve this without using session variable. being many to many there needs to be a way that the system knows what client is currently in use. If i can get around this then the database seeding wont be a problem.

Thanks!

bobbybouwmann's avatar

You can still set something in the session, but you have to do that before you run the query. Otherwise it won't work. I would personally use a normal scope and be explicit in every query instead of the global query scope. You can wrap all queries in a repository to make them reusable if you wish ;)

danep's avatar
Level 1

Thanks for your help sofar, I have just found the withoutGlobalScopes() method. I suspect that this would work for the seeding of data provided the data constraints were accounted for in the seeding. Is this suitable in your opinion to prevent unauth access to other customers inadvertently?

bobbybouwmann's avatar

@danep Sure, but do note that the functionality will be different than everywhere else in your code. But if this works for you it's perfectly fine ;)

Please or to participate in this conversation.