joemottershaw's avatar

Cast Array to an Object in Controller and then pass to View

I know you can obviously pass through an array to the view and use {{ $var['key'] }} for example. But I was wondering if there was a way in Laravel to cast the array to an object and then pass it through the view so you can use dot notation instead.

Mainly cause I want a little consistency in my template files, since I have {{ $var['key'] }} in some places but dot notation in others, just kind of want to have it all the same if it's possible, I also understand that it's not a massive deal, it's more that I want to know if it's possible because I prefer it...

Controller

public function index() {

    $user = Auth::user();
    $page = array(
        'title' => 'Hello World',
        'template' => 'welcome',
    );

    return View('index', array(
        'user' => $user,
        'page' => $page,
    ));

}

View

<html>
<head>
    <title>{{ $page['title']; }}</title>
</head>
<body id="{{ $page['template'] }}"></body>
    <p>Hello, {{ $user->name }}!</p>
    <p>Your email address is {{ $user->email }}</p>
</body>
</html>

So by consistency I mean I would like to be able to set the page title/template using {{ $page->title }} and {{ $page->template }}. I might just be missing something really obvious and there's some helper function like array_to_object(), but I just can't seem to find anything and I'm still relatively new to Laravel and MVC frameworks in general.

I have tried the following method but to no success:

$object = (object) $array;

And also:

$object = new stdClass();

foreach ($array as $key => $value) {
    $object->$key = $value;
}

Obviously changing $object and $array to fit my scenario and passing it to the view.

0 likes
2 replies
bestmomo's avatar
Level 52

Should work :

public function index() {

    $user = Auth::user();
    $page = array(
        'title' => 'Hello World',
        'template' => 'welcome',
    );

    $page = (object)$page;

    return View('index', array(
        'user' => $user,
        'page' => $page,
    ));

}
4 likes
joemottershaw's avatar

Hm, now I've very confused, I just set up a clean route/controller/view with no other extras, tried that method again and it's worked this time. It must of been something else causing the problem somewhere in my controller. So that's rather embarrassing... but thank you for confirming. I couldn't understand earlier why it didn't work before, I just thought Laravel was treating it differently than expected and I couldn't understand why, but it wasn't even the problem in the first place, ha.

And just for any one else reading, it's of course possible to inline it like usual:

$page = (object) array(
    'title' => 'Hello World',
    'template' => 'welcome',
);

Thank you @bestmomo

1 like

Please or to participate in this conversation.