简体   繁体   中英

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?

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'));

you can try as below

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

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()]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM