Controller method - Ajax request I'm quite new to Laravel, and I'm not sure what am I doing is the best practice.

I'd like to return JSON if the request is Ajax, or return a view otherwise. This is the way I made it, and it works fine, but I'm not sure if this is the best way(it seems long winded). I'd really like to hear your suggestions.

public function store()
{
    $input = Input::all();

    if(!$this-&gt;settings-&gt;fill($input)-&gt;isValid())
    {
        if ( Request::ajax() ){
            return $this-&gt;jsonFailure(array(
                'errors' =&gt; $this-&gt;settings-&gt;errors
            ));
        }
        else{
            return Redirect::route('admin.settings.create')
                -&gt;withInput()
                -&gt;withErrors($this-&gt;settings-&gt;errors);
        }
    }

    $this-&gt;settings-&gt;save();

    if ( Request::ajax() )
        return $this-&gt;jsonSuccess('success');
    else
        Redirect::route('admin.settings.index');
}
The only problem with this approach is that as you add more methods, you are going to end up with an awful lot of repeated if (Request::ajax()) ... blocks all over your code.

Here's what I do for my sites:

&lt;?php
class ApiController extends Controller {
    protected function makeResponse($data, $isError = false, $redirectToIfNotAjax = '/') {
        if (Request::ajax()) {
            if ($isError) {
                return $this-&gt;jsonFailure(array(
                    'errors' =&gt; $data
                ));
            } else {
                return $this-&gt;jsonSuccess($data);
            }
        } else {
            if ($isError) {
                return Redirect::route($redirectToIfNotAjax)
                    -&gt;withInput()
                    -&gt;withErrors($data);
            } else {
                Redirect::route($redirectToIfNotAjax);
            }
        }
    }
}


(This is not exactly the same as what I am using, but it's pretty close.)

Then, inherit your controllers from ApiController instead of just Controller.

Here is what your example would look like:

public function store()
{
    $input = Input::all();

    if(!$this-&gt;settings-&gt;fill($input)-&gt;isValid())
    {
        return makeResponse($this-&gt;settings-&gt;errors, true, 'admin.settings.create')
    }

    $this-&gt;settings-&gt;save();

    return makeResponse('success', false, 'admin.settings.index')
}


Much cleaner!