I have this piece of code
$generate_data_by_user = function($user) {
//validate ...
return [
'identity' => $user['id'],
'name' => $user['real_name']
];
}
User::where('age', '>', 18)->get()->map($generate_data_by_user); // pass
or
Db::table('code_user')->where('age', '>', 18)->get()->map($generate_data_by_user); //fail
Can you explain me db('code_user')->where('age', '>', 18)->get()->map($generate_data_by_user);
that what you are doing here? @HongjiangHuang
I don't understand what you're trying to say... Maybe I made a mistake it should be Db::table('code_user')->where('age', '>', 18)->get()->map($generate_data_by_user); //fail
The db function is just a helper function I added for myself
I just want to say that a lot of times we get used to $item[key], Because Model implements \ArrayAccess, but , Db return value not implements \ArrayAccess, This makes me need to determine the source of data is Model or Db
It's not clear - what is the exact issue you are describing here?
Db::table('code_user')->where('age', '>', 18)->get()->map($generate_data_by_user); //fail
This tails with your closure because your receive a stdClass object with properties hydrated from the DB result but you are trying to access it like an array.
This is exactly as https://github.com/laravel/framework/issues/25821#issuecomment-425611503 described: Eloquents user model implement \ArrayAccess that's why $user['id'] works on Eloquent results but not on DB results.
TL;DR: if you _really_ have to use the same closure, use $user->id or even better, not mix them.
I just wanted to make a suggestion, Db return stdClass object implements ArrayAccess interface.
Thanks @HongjiangHuang
Unfortunately this GitHub area is not for ideas, suggestions etc. This is only for issues/bugs with the framework code itself. You are able to open a ticket at https://github.com/laravel/ideas
Alternatively you are able to open a PR using the Contributions guidelines: https://laravel.com/docs/5.7/contributions#which-branch and add the interface for Taylor to decide to accept or not.
Most helpful comment
I just wanted to make a suggestion, Db return stdClass object implements ArrayAccess interface.