Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel | eloquent foreach not working

I am trying to retrieve all non admin users from my user table. like so

$agents = User::where('is_admin','=', 'false')->get();

//didn't work
foreach ($agents as $agent=>$value) 
{
    echo "{$agent}=>{$value}"."<br>";
}

//tried dumping
dd($agents);

but It didn't work so I tried dumping the variable to check if it had any results, I have one non-admin as of now: and here is the output

Collection {#219 ▼
#items: array:1 [▼
    0 => User {#222 ▼
      #casts: array:1 [▶]
      #fillable: array:6 [▶]
      #hidden: array:2 [▶]
      #connection: null
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:10 [▶]
      #original: array:10 [▶]
      #dates: []
      #dateFormat: null
      #appends: []
      #events: []
      #observables: []
      #relations: []
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [▶]
      #rememberTokenName: "remember_token"
    }
  ]
}

Please Help

like image 551
Sapnesh Naik Avatar asked Apr 07 '17 06:04

Sapnesh Naik


2 Answers

$agents = User::where('is_admin','=', 'false')->pluck('value', 'agent'); 

foreach ($agents as $agent=>$value) {
echo "{$agent}=>{$value}"."<br>";
}

Using pluck you will convert the object to a array, so you can use the foreach the way you want with the key => value.

If you need to access other attributes of the model, you will need to do something like this:

$agents = User::where('is_admin','=', 'false')->get(); 

foreach ($agents as $agent) {
echo "{$agent->id}=>{$agent->name}"."<br>";
}

This way you just need to use $agent and -> followed by the attribute you want.

like image 60
Big Boss Avatar answered Nov 18 '22 13:11

Big Boss


Your controller should be like:

public function index() {

    $agents = User::where('is_admin','=', 'false')->get();
    return view('viewfile', compact('agents'));
}

And then in that view file make the foreach loop in blade view

@foreach ($agents as $agent)
     {{ $agent->name }}
@endforeach
like image 39
lewis4u Avatar answered Nov 18 '22 11:11

lewis4u