Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel define default layout from controller in good way

Tags:

php

laravel

I googled two hours, but not found answer. Maybe you can help.

When I define in MyController:

class MyController extends Base_Controller {
    public $layout = 'layouts.default';

    public function get_index() {
        $entries = Entry::all();
        return View::make('entries.index')
            ->with('entries', $entries);
        }
    }
}

In entries\index.blade.php:

@section('content')
    <h1>Test</h1>
@endsection

And in layouts\default.blade.php:

<!DOCTYPE html>
<html>
<body>
    @yield('content')
</body>
</html>

Nothing is displaying. And I don't understand why. When I am replacing in MyController return part with:

$this->layout->nest('content', 'entries.index', array(
    'entries' => $entries
));

Then all is working, but.. It looks not clean and I don't like it. When adding in every view @layout('layouts.default') all is working good too, but it is not DRY. For example, in RoR I don't need to do such things in Controller.

How can define in MyController one layout and use return View::make (I think that this is right way) or how can do it better?

like image 971
Orbitum Avatar asked Nov 21 '12 20:11

Orbitum


1 Answers

To use layouts in controllers, you must specify:

public $layout = 'layouts.default';

You can also not return in the method as it will override the use of $layout. Instead, to embed your content within the layout you use:

$this->layout->nest('content', 'entries.index', array('entries' => $entries));

No need to return anything in your method now. This will fix it.


Edit:

"Beautiful Ways?"

$this->layout->nest('content', 'entries.index')->with('entries', $entries);


$this->layout->content = View::make('entries.index')->with('entries', $entries);


$this->layout->entries = $entries;
$this->layout->nest('content', 'entries.index');
like image 141
Joel Larson Avatar answered Oct 23 '22 15:10

Joel Larson