skip to Main Content

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);
}

3

Answers


  1. 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.

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search