Reputation: 179
I have a branch code column (in array value) in table Users.
e.g branch_code in Table User= ["01234","03333","02030"]
And I have a report page where user can select the branch with a select option in blade based on the user's branch code
So here is my controller
$user = Auth::user();
$user_branch = $user->branch_code;
$region = Branch::whereIn('branch_code',[$user->branch_code])->get();
but i get null data, if i run dd($user_branch)
will show
["01234","03333","02030"]
How to show the branch from array value in DB?
Upvotes: 2
Views: 1269
Reputation: 577
So what you are getting back when doing dd($user_branch)
is a string not an array. When doing whereIn()
, the second parameter needs to be an array.
What you need to do is cast branch_code as an array in User
model. Here is a link to the laravel documentation for more info:
https://laravel.com/docs/8.x/eloquent-mutators#array-and-json-casting
By casting it as an array you can then use it as an array in controller or view.
class User extends Model
{
/**
* The attributes that should be cast.
*
* @var array
*/
protected $casts = [
'branch_code' => 'array',
];
}
Upvotes: 1