11 months ago

How to return multiple variables to a view and use them

Posted 11 months ago by uhbc

How do I use multiple variables that are returned by different functions in the controller. Please take a look at the codes to understand what I exactly mean.

Here is the controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\User;
class HomeController extends Controller

    public function function1(){
      // https://site.com/home
      $res = \DB::table("somedb")->get();
      return view('home', ["variable1"=>$res]);
    public function function2($id){
      // https://site.com/home/1
      $res = \DB::table("somedb")->where("id", $id)->get();
      return view('home', ["variable2"=>$res]);


And here is the home.blade.php

<html lang="en" dir="ltr">
    <meta charset="utf-8">

        @foreach($variable1 as $row)
          <td>[a button to edit this row etc..]</td>
        @foreach($variable2 as $row)
          <td><input type="text" name="name" value="{{$row->name}}"></td>
          <td>[a button to submit etc..]</td>

When I'm trying to this, giving me an error of "Undefined variable: variable2 (View: .../home.blade.php)"

The reason i wanna do this is that i dont wanna create another view.

What should I do

Please sign in or create an account to participate in this conversation.