uhbc
5 months ago
161
4
Laravel

How to return multiple variables to a view and use them

Posted 5 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">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <table>
      <thead>
        <tr>
          <th>ID</th>
          <th>Name</th>
          <th>Process</th>
        </tr>
      </thead>

      @if(isset($variable1))
      <tbody>
        @foreach($variable1 as $row)
        <tr>
          <td>{{$row->id}}</td>
          <td>{{$row->name}}</td>
          <td>[a button to edit this row etc..]</td>
        </tr>
        @endforeach
    </tbody>
    @else
      <tbody>
        @foreach($variable2 as $row)
        <tr>
          <td>{{$row->id}}</td>
          <td><input type="text" name="name" value="{{$row->name}}"></td>
          <td>[a button to submit etc..]</td>
        </tr>
        @endforeach
      </tbody>
    @endif
    </table>
  </body>
</html>

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.