How to convert object of stdClass to array in Laravel
12,792
Solution 1
you have hell lot of mistake in your blade file
@if($contactusd)
<br><br>
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Message</th>
</tr>
</thead>
@foreach($contactusd as $item)
<tr>
<td>{{ $item->name }}</td>
<td>
<ul>
<li> Email: {{ $item->email}}, Massage: {{$item->message }}</li>
</ul>
</td>
<td>{{ $item->created_at}}</td>
</tr>
@endforeach
</table>
@else
<p style="font-size: 18px">No information...</p>
@endif
or
$contactusd = ContactUS::get_content(self::$data)->toArray();
return view('cms.contactus', $contactusd);
Solution 2
To convert an object to array (as is your question) use $array = (array) $object;
Solution 3
If you getting data is in std class ,
you can write like this in view page {{ $item->name }}
If you getting data is in std class ,
you can write like this in view page {{$item['message']}}
backside write like this
$sql = "SELECT cu.*,name,email,message FROM contactus cu "
. "ORDER BY cu.created_at DESC ";
$data['contactusd'] = DB::select($sql)->get()->toArray();
Solution 4
Try this..
$sql = "SELECT cu.*,name,email,message FROM contactus cu "
. "ORDER BY cu.created_at DESC ";
$data['contactusd'] = DB::select($sql)->get()->toArray();
Author by
Pioneer2017
Updated on August 01, 2022Comments
-
Pioneer2017 almost 2 years
I am getting the next error when trying to display a view in Laravel :
"Cannot use object of type stdClass as array (View: C:\xampp\htdocs\mysite\resources\views\cms\contactus.blade.php)".
My Controller:
public function contactus(){ ContactUS::get_content(self::$data); return view('cms.contactus', self::$data); }
My Model:
class ContactUS extends Model { public $table = 'contactus'; public $fillable = ['name','email','message']; static public function get_content(&$data){ $sql = "SELECT cu.*,name,email,message FROM contactus cu " . "ORDER BY cu.created_at DESC "; $data['contactusd'] = DB::select($sql); } }
My view:
@extends ('cms.cms_master') @section('cms_content') <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <h1 class="page-header">Contact us form information</h1> @if($contactusd) <br><br> <table class="table table-bordered"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Message</th> </tr> </thead> @foreach($contactusd as $item) <tr> <td>{{ $item['name']}}</td> <td> <ul> <li> Email: {{ $item['email']}}, Massage: {{$item['message'] }}</li> @endforeach </ul> </td> <td>{{ $item[created_at]}}</td> </tr> </table> @else <p style="font-size: 18px">No information...</p> @endif </div> @endsection
-
aynber over 6 yearsWell, you can use it as an object instead (
$item->email
), or convert it to an array@foreach($contactusd as (array)$item)
-
aynber over 6 yearsPossible duplicate of How do I convert an object to an array?
-
Admin over 6 yearsnah he is asking for laravel and however you should prefer eloquent instead of Raw Queries.
-