0
votes

It might just be me coming from a more restricted java background, but I'm feeling the connection between views and controllers in Laravel is error prone. For example, consider a controller looking something like this

ReceiptController extends BaseController {
    ...
    public function show() {
        $data = array($receipt, $offer);
        View::make('registration', $data);
    }
}

and a view which depends on a receipt object and an offer string

...
<div id="receipt">
    <h1>Receipt</h1>
    {{$receipt->items}}
    @if ($receipt->price > 10000)
        <p>{{$offer}}</p>
    @endif;
</div>
...

What if a controller somewhere don't include the offer string? Worst case scenario it might go unnoticed until someone purchase something with a price over 10000. How would I go about throwing an error if the controller doesn't pass all variables required to make the view? Bonus if it also makes an IDE such as PHPStorm recognize the variables.

2

2 Answers

1
votes

You could use a view composer, and ensure that whenever your receipt view is called, a offer is always included. That way you know the object is always passed.

View::composer('receipt', function($view)
{
    $view->with('offer', Offer::get(1));
});

Or you could just handle it directly in your view

<div id="receipt">
    <h1>Receipt</h1>
    {{$receipt->items}}
    @if ($receipt->price > 10000)
       <p>{{$offer or 'Sorry - no special available'}}</p>
    @endif;
</div>

Lastly - the 'best' option is to always test your code, and check your view is always called with a $offer variable

 $this->assertViewHas('offer');
0
votes

That kind of logic if intented to work in the Controller, if the price is higher than a value, set a $var = false and check if in the view.

if($receipt->price > 10000) {
   $offer = $offer;
} else {
   $offer = false;
}

And about the compatibility between PHPStorm and Blade Template Engine, PHPStorm 7.1 doesn't support it, but you help to build a better world voting for it for the next version: http://youtrack.jetbrains.com/issue/WI-14172