breekoy
breekoy

Reputation: 128

return redirect() is not working after a failed validation

I have a form where users can edit a branch's info, once the user submits that form, the update() method checks for the validity of the submitted data such as the description must be unique to every subscriber. While the validation WORKS, it doesn't redirect to the exact url/page that I want if the validation fails. It stays in the same edit form.

here's the code of my update() method:

public function update(Request $request, $id)
{
    $description = $request->input('description');
    $message     = $request->input('message');
    $subscriber_id = auth()->user()->subscriber_id;

    $messages = [
        'description.unique' => 'Branch already exists!',
    ];

    $this->validate($request, [
        'description' => Rule::unique('branches')->where(function ($query) use($subscriber_id) {
            return $query->where('subscriber_id', $subscriber_id);
        })
    ], $messages);

    Branch::where('id', $id)->update([
        'description'   => $description,
        'message'       => $message,
    ]);

    return redirect('branches')->with('success', 'Branch info successfully updated!');
}

Note: the url of the edit form is /branch/edit/{id} while the page I want to redirect after submission is /branches.

Is my validation wrong? Did I miss something?

Thanks! :)

Upvotes: 0

Views: 553

Answers (1)

LLai
LLai

Reputation: 13396

According to the laravel docs you can redirect to a different route by using the Validator facade

public function update(Request $request, $id)
{
    $description = $request->input('description');
    $message     = $request->input('message');
    $subscriber_id = auth()->user()->subscriber_id;

    $messages = [
        'description.unique' => 'Branch already exists!',
    ];

    $validator = Validator::make($request->all(), [
        'description' => Rule::unique('branches')->where(function ($query) use($subscriber_id) {
            return $query->where('subscriber_id', $subscriber_id);
        })
    ],
    $messages);

    if ($validator->fails()) {
        return redirect('/branches')
            ->withErrors($validator)
            ->withInput();
    }

    Branch::where('id', $id)->update([
        'description'   => $description,
        'message'       => $message,
    ]);

    return redirect('branches')->with('success', 'Branch info successfully updated!');
}

Make sure you use the Validator facade at the beginning of your controller file use Validator;

Upvotes: 1

Related Questions