Kin
Kin

Reputation: 4596

How to setup layouts in Laravel?

By example I'm trying to create the layout. My base controller looks like this:

class BaseController extends Controller {
    protected $layout = 'layouts.default';
}

Then i extend it via user controller like which looks like this:

namespace Site;

use View;

class UserController extends \BaseController {
    
    public function index()
    {
        $this->layout->content = View::make('site/user/index');
        // return View::make('site/user/index');
    }
}

But in the end I get the following error Attempt to assign property of non-object. var_dump shows that $this->layout is the string, not the object.

Basically i just want to do return View::make('site/user/index');.

Upvotes: 1

Views: 5847

Answers (3)

Hayk Aghabekyan
Hayk Aghabekyan

Reputation: 1087

If you are using Laravel 5, you can do it like this (I am not sure if it is the best way)

return view("layout/here", [
    "content" => view("dynamic/content/here")
]);

then in your view you can do this

 <?php echo $content; ?>

of course, if you are not using blade.

Upvotes: 1

menjaraz
menjaraz

Reputation: 7575

Assuming that all your blades are OK and you insist using Controller layout because Laravel allow it as an option, add this snippet to your BaseController to fix that:

protected function setupLayout()
{
    if ( ! is_null($this->layout))
    {
        $this->layout = View::make($this->layout);
    }
}

Upvotes: 2

Laurence
Laurence

Reputation: 60048

This is how I prefer to do layouts.

Firstly - I DONT set protected $layout = 'layouts.default'; in the controller - I just leave it out.

Second - I setup a template like this:

app/views/layouts/master.blade.php

<h1>This is my master template</h1>

@yield('content')

<h5>This is my footer</h5>

Then in my various views

app/views/user/index.blade.php

@extends('layouts.master')

@section('content')
    This is the user section
@stop

This way the layout template is defined in the view, not the controller, which is where I think it should be (the controller shouldnt know/care about what template your view uses).

Upvotes: 3

Related Questions