Home > Back-end >  i have this error when i send post request in postman
i have this error when i send post request in postman

Time:01-23

i get error when i send request in post man

the error: ErrorException: Undefined array key "value" in file

thw code:

public function search(Request $request) {
    $request = $request->all();

    $models = Course::query()
            ->where('title', 'like', '%' . $request['value'] . '%')
            ->where(['deleted' => '0'])
            ->get();
    return response()->json($models);
}

CodePudding user response:

Dump out your $request and have a look at it, like :

dd($request); 

You probably want to access the values like :

$request->input('value');

instead of trying to access it as an array.

CodePudding user response:

you can make the following changes , so that it works dynamically based on the given

public function search(Request $request)
    {
        $request = $request->all();

        $models = Course::query()
            ->when(array_key_exists('value', $request), function ($query) use ($request) {
                $query->where('title', 'like', '%' . $request['value'] . '%');
            })
            ->where(['deleted' => '0'])
            ->get();
        return response()->json($models);
    }

here we have when statement to check whether this key exist or not , in case of non existence it won't execute with that particular key else it works as desired.

when(array_key_exists('value', $request), function ($query) use ($request) {
            $query->where('title', 'like', '%' . $request['value'] . '%');
        })

you can also modify when statement, or if you want more conditional statement than you can also append those inside the above-mentioned statement.

CodePudding user response:

del one line and use

&request->value;

like that

public function search(Request $request) {
$models = Course::query()
        ->where('title', 'like', '%' . $request->value . '%')
        ->where(['deleted' => '0'])
        ->get();
return response()->json($models);
}
  • Related