user2094178
user2094178

Reputation: 9454

Retrieving view data in a view composer

If I do the following in this view composer:

View::composer('product.edit', function($view)
{
    $viewdata = $view->getData();
    dd($viewdata);
});

I can see in the output that exists 'language_id', however I don't know how to retrieve it, since $viewdata['language_id'] will throw an exception.

How should I go about this?

Update:

The accepted answer led me to discover that when a presenter is involved in this operation, the model will be available in the offset, here is the final code:

View::composer('product.edit', function($view)
{
    $data = $view->offsetGet('product')->toArray();
    echo $data['language_id'];
    exit;
});

Upvotes: 3

Views: 1177

Answers (2)

Epoc
Epoc

Reputation: 7486

Worth noting you can also access view data using the attribute syntax (at least starting Laravel 8):

$languageId = $view->product->language_id ?? null;

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

You may try this:

$language_id = $view->offsetGet('language_id');

Following public methods are available in the $view object (An instance of Illuminate\View\View)

0 => string '__construct' (length=11)
1 => string 'render' (length=6)
2 => string 'renderSections' (length=14)
3 => string 'with' (length=4)
4 => string 'nest' (length=4)
5 => string 'withErrors' (length=10)
6 => string 'getEnvironment' (length=14)
7 => string 'getEngine' (length=9)
8 => string 'getName' (length=7)
9 => string 'getData' (length=7)
10 => string 'getPath' (length=7)
11 => string 'setPath' (length=7)
12 => string 'offsetExists' (length=12) 
13 => string 'offsetGet' (length=9)
14 => string 'offsetSet' (length=9)
15 => string 'offsetUnset' (length=11)
16 => string '__get' (length=5)
17 => string '__set' (length=5)
18 => string '__isset' (length=7)
19 => string '__unset' (length=7)
20 => string '__call' (length=6)
21 => string '__toString' (length=10)

You may also try something like this:

if($view->offsetExists('language_id')) {
    $language_id = $view->offsetGet('language_id');
}

Upvotes: 4

Related Questions