Raheel Khan Raheel Khan - 4 months ago 266
PHP Question

Laravel - check if Ajax request

I have been trying to find a way to determine ajax call in Laravel but i don't find any document regarding it.

I have a

index()
function which i want to handle situation differently based on the nature of request. Basically this is a resource controller method that is bound to GET request.

public function index()
{
if(!$this->isLogin())
return Redirect::to('login');

if(isAjax()) // This is what i am needing.
{
return $JSON;
}

$data = array();
$data['records'] = $this->table->fetchAll();

$this->setLayout(compact('data'));
}


I know the other methods of determining the Ajax request in PHP but i want something specific to Laravel.

Thanks

Updated:

I tried using

if(Request::ajax())
{
echo 'Ajax';
}


But i am receiving error :
Non-static method Illuminate\Http\Request::ajax() should not be called statically, assuming $this from incompatible context


The class shows that this is not a static method.

Answer

Maybe this helps. You have to refer the @param

         /**       
         * Display a listing of the resource.
         *
         * @param  Illuminate\Http\Request $request
         * @return Response
         */
        public function index(Request $request)
        {
            if($request->ajax()){
                return "AJAX";
            }
            return "HTTP";
        }