Home > database >  Laravel Ajax is working with post route but not working with resource route post method
Laravel Ajax is working with post route but not working with resource route post method

Time:04-19

Ajax code

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        url: "/vouchersave",
        type: "post",
        dateType: "JSON",
        data: voucherData,
        success:function(data){
            console.log(data);
        },
    });

The ajax is working with this post route

Route::post('/vouchersave', function(Request $request){
    $input = $request->all();
    Log::info($input);
    return response()->json(['success'=>'Got Simple Ajax Request.']);
});

But when I change to resource route store method, it shows 500 internal server error

Route::resource('voucher', VoucherController::class, ["name" => "voucher"]);

public function store(Request $request)
    {
        $input = $request->all();
        Log::info($input);
        return response()->json(['success'=>'Got Simple Ajax Request.']);
    }

Ajax code for resource route controller

$.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        url: "/voucher",
        type: "post",
        dateType: "JSON",
        data: voucherData,
        success:function(data){
            console.log(data);
        },
    });

The error is

[2022-04-18 09:26:55] local.ERROR: Class "App\Http\Controllers\Log" not found {"userId":1,"exception":"[object] (Error(code: 0): Class "App\Http\Controllers\Log" not found at /home/kyaw/project/spa/spa_salon/app/Http/Controllers/VoucherController.php:53) [stacktrace]

CodePudding user response:

First, you have to import the controller like,

use App\Http\Controllers\VoucherController;

And you used it in class,

Route::resource('voucher',[VoucherController::class, 'store']);

CodePudding user response:

The error causing of 500 internal server error is Log::info() in store method of controller.

CodePudding user response:

The problem is that you call Log::info($input); without using the namespace of Log. You will need to use the proper namespace of the Log class, like

use Illuminate\Support\Facades\Log;

The above assumes that you are using the Log of Illuminate. If that's not the case, then you will need to change the namespace path to the one you are actually using.

  • Related