laravel orm:来自几乎相同查询的不同结果

I've a very big doubt about how works laravel for a very simple thing:

If I call:

$companies=User::All();

Then I can use statement like this in a forach:

foreach($companies as $company)
$company['new_field']= 'something';

If i'm limiting the output of the query like:

$companies = DB::table('companies')
            ->select('id','name','email','business_name',...)->get();

The things doesnt work as before,

  • I try with or without the ->get()
  • I try to convert with ->toArray() (errors rised)
  • I try with put() and push() for collections method and agains errors...

How can I add a field in every item of the collection just to pass it to a view?

Try like this, hope it works for you:

$users=User::select('id','name','email','business_name',...)->get()->toArray();

and then use foreach loop like this:

foreach($users as $key => $value ){
    $users[$key]['newField'] = "Demo";
}

If you are using Laravel and model in it so there is a better way to add custom attribute or field here is what i do for custom field

For Example :

There is a Model Name User so in User Model add a property name appends like :

class User extends Model
{
    protected $appends = ['new_field'];

    public function getNewFieldAttribute() // defining field logic here
    {
        return // your code
    }

So you no need to use foreach and looping and adding new field

for more have a look on laravel doc : https://laravel.com/docs/5.5/eloquent-mutators#accessors-and-mutators

Suggestion

you can limit your output with Model too.

User::select('id','name','email','business_name',...)->get();

if you are making an array like

User::select('id','name','email','business_name',...)->get()->toArray();

so this will also give you your custom field