dynamically load view in laravel 5

Sometime we have some requirements to load a view dynamic based on query variable or other things. So in this article we will see how to conditionally or dynamically load view in laravel 5. I am using controller function for this to load view and call the controller function from routes. So let’s see how we can achieve to load a view dynamically in laravel 5.

Using Controller

Routes

Let’s first make a route to call our controller function. So go to /routes/web.php and add your routes.

// Simple get route
Route::get('myviews','[email protected]');
// Or you can use named route
Route::get('myviews','[email protected]')->name('my');

Controllers

So i have MyController class under the /app/Http/Controllers/MyController.php. Which i have used for routes. Let see below code for controller to dynamically load view in laravel 5.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class MyController extends Controller
{

/**
 * Show the views dynamically.
 * @return \Illuminate\Http\Response
 */

    public function index(Request $request)
    {
	// Query to get viewname from databse. here $_GET['id'] getting from query string.
	$viewdata = DB::table('Views')->where('View_ID', '=', $_GET['id'])->get();
	// Getting viewname from db and call view with passing some data.
	return view($viewdata->viewname, ['data' => $str]);    
    }
}

Here you can make any condition according to your need to dynamic load a view. Like you are calling api from controller and passing views conditionally etc.

Using routes

You can also load a view dynamically from routes so let’s have a look how we can load views dynamically. I am getting a view name from query string and getting it in routes to load. Also you can use direct query to get view from db according to passed variables.

Route::get('/payment', function () {
    // Get the full query string.
    $qstring = Request::all(); 
    // Get the view name from query string 
    if(isset($qstring['view']) &amp;&amp; !empty($qstring['view'])){
      // Load the view
      return view($qstring['view']);  
    }
});

Conclusion

That’s enough i think, i just explained simply may be there is many types of requirements to dynamically load view in laravel 5. There we can do this done by many ways and also many of examples i am not including but i think it will sure give you a little twick to done your requirements.

Cheerss! happy coding!

Adam Brown
Please follow and like us:

Leave a Comment