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
$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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With