11

How to check request is ajax or not in Laravel 8

 2 years ago
source link: https://www.laravelcode.com/post/how-to-check-request-is-ajax-or-not-in-laravel-8
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How to check request is ajax or not in Laravel 8

  445 views

  7 months ago

Laravel

Sometime in your Laravel application, you might need to check if request is ajax then response json data else return view in response. This helps to manage Ajax request in same route when you want to load view first and then then send ajax request to view data.

In this article, we will learn how you can check request is ajax or not in controller method. In Laravel, ajax() method checks if request is from ajax or not and return true or false.

You can use Request facade that checks current request or you can use Request instance.

Request facade example:

/**
 * Load resource data.
 *
 * @return void
 */
public function index(Request $request)
{
    if($request->ajax()) {
        // ajax request
        return response()->json(['status' => 'success']);
    }

    return response()->json(['status' => 'fail']);
}

Request instance example.

/**
 * Load resource data.
 *
 * @return void
 */
public function index()
{
    if(Request::ajax()) {
        // ajax request
        return response()->json(['status' => 'success']);
    }

    return response()->json(['status' => 'fail']);
}

I hope it will help you. Thanks for giving time in reading the article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK