2

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?

1 Answer 1

1

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',
    ];
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.