Jake2018
Jake2018

Reputation: 93

PHP Laravel - Returning view from a sub-directory

I'm trying to return a view from a sub-directory however when using the code below I get the error "Undefined variable: folder1"

Route::get('/', function () {
return view("folder1/page1");
});

or

Route::get('/', function () {
return view("/folder1/page1");
});

or

Route::get('/', function () {
return view("folder1.page1");
});

The view "page1" is located in a folder called folder1, for example...

How do you return a view that's not located in the same directory?

Upvotes: 1

Views: 3977

Answers (3)

Donnicias
Donnicias

Reputation: 186

In laravel, by default views are stored in resources/views directory. Your view, page1.blade.php file is in resources/views/folder1 directory. To return the view, we can use the global view helper as follows,

return view('folder1.page1');

For your case above, you can do this

Route::get('/',function(){
  return view('folder1.page1');
});

If you want to pass data into the view, there are many methods to do that, you can use this

$data1= 'Sample data 1';
return view('folder1.page1',['data1'=>$data1]);

Or

$data1 = 'Sample data 1';
returnn view('folder1.page1')->with('data1',$data1);

Or

$data1 = 'Sample data 1';
return view('folder1.page1')->compact('data1');

Or

$data1 = 'Sample data 1';
return view('folder1.page1',compact('data1'));

Upvotes: 3

Niraj Savaliya
Niraj Savaliya

Reputation: 189

you can try as below

Route::get('/', function () {
   return view("folder1.page1",compact('products'));
});

Upvotes: 1

Jaime Rojas
Jaime Rojas

Reputation: 559

The problem is not the view itself, the problem is that you're not passing the view the $product variable it's using within the view to render data from a product / products.

Try something like this:

Router::get('/', function() {
  return view('folder1.page1', ['products' => App\Product::all()]);
}

Upvotes: 0

Related Questions