Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render web and mobile views in Laravel

I have two blade files for each route, one for web and one for mobile devices. I don't know proper way to handle requests. Is that a proper way:

At the end of each controller function (For each request)

If it is mobile (via Jenssegers)
    View::make(file_mobile.blade.php)
else
    View::make(file_web.blade.php)

What would you suggest?

like image 527
horse Avatar asked Jan 19 '15 17:01

horse


2 Answers

One option would be to use a library like Laravel Agent.

https://github.com/jenssegers/Laravel-Agent

if ( Agent::isMobile() ) {
    View::make("file_mobile.blade.php");
} else {
    View::make("file_web.blade.php");
}

Rather than repeat this in each controller method, you may want to abstract this out. A response macro seems like a good option, maybe something like:

Response::macro('ress', function($viewname)
{
    if ( Agent::isMobile() ) {
        return View::make($viewname . "_mobile.blade.php");
    } else {
        return View::make($viewname . "_web.blade.php");
    }
});

So that you can call this in your controller:

return Response::ress('file');

This is all untested code, just to point you in the direction of one possible solution.

like image 114
jszobody Avatar answered Oct 17 '22 22:10

jszobody


jszobody's answer is probably best since you already have the views for each version made, but in the future, I would consider controller layouts.

Basically what you would do is build two layouts, one for mobile and one for non-mobile and set them in the constructor of BaseController. These layouts would contain all the necessary styling, navbar or whatever else all your views should have in common.

public function __construct()
{
    $this->layout = Agent::isMobile() ? 'layouts.mobile' : 'layouts.nonMobile';
}

Both layouts would have a @yields('content') to give it a content section and all your views should only be worried about the content that shows in the layouts.

Then all you have to do is instead of returning a view in your controllers, simply set the content section in the layout.

$this->layout->content = View::make('user.content');`

This is what I do on my personal projects and it usually works out quite well. In the event you want to experiment with a new site layout or need to add a mobile layout or even an admin layout, simply create the layout, modify BaseController::__constructor() to set it when you need to, and you are done.

like image 33
user1669496 Avatar answered Oct 17 '22 22:10

user1669496