Home > Software engineering >  How to return multiple views in a Laravel controller?
How to return multiple views in a Laravel controller?

Time:09-29

Inside a controller in Laravel I have this:

public function index()
{
    $users = User::orderBy('name', 'asc')->paginate(13);
    $users2 = User::all();

    return view('contatos.index')->with('users', $users);
    return view('auth.register')->with('users', $users2);
}

I know isn't right, it's just to demonstrate my logic. Is there a way to unite these two returns in a single return? Or even a much shorter form for this code?

CodePudding user response:

You can include many views inside a single view using the @include directive:

combined.blade.php:

@include('contatos.index')
@include('auth.register')

Then in your controller:

public function index()
{
    $users = User::orderBy('name', 'asc')->paginate(13);
    $users2 = User::all();

    return view('combined')->with('users', $users);
}

There are many variants of include, like includeWhen of includeIf, they are all described in the documentation: https://laravel.com/docs/8.x/blade#including-subviews

However, the key point to understand is that you always return only one thing (in your case, one view).

This view can be composed of multiple parts and this compositing job is the role of Blade.

CodePudding user response:

You can use view incude

public function index()
{
    $users = User::orderBy('name', 'asc')->paginate(13);
    $users2 = User::all();

    return view('contatos.index', ['users1'=> $users, 'users2'=> $user2]);
}

Inside contatos.index blade

HTML Elements

@include('auth.register', ['users2' => $users2])

HTML Elements

Try this, Tell me If anything wrong happened.

  • Related