uhbc's avatar
Level 1

How to return multiple variables to a view and use them

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

0 likes
4 replies
Sergiu17's avatar

@uhbc if you don't want to create another view, then do not create another function

public function function1($id = null)
{
    if($id) {
        $result = \DB::table('somedb')->where('id', $id)->get();
    } else {
        $result \DB::table('somedb')->get();
    }
    
    return view('home', ['result' => $result]);
}

Now find a way to do a if statement in the view

@if( count($result) > 1 ) // collection
@else // single record
1 like
Cronix's avatar

Typically, you'd have 2 different methods for what you're doing. An index method traditionally returns all results for something, and a show method shows a specific result (like by id). I wouldn't mix those into a single controller/view.

Your controller logic will be simpler, as well as the individual view files since they won't have as much going on in them.

2 likes

Please or to participate in this conversation.