mardi 16 juin 2020

Is there a way to return both a redirection and response code at the end of a submission

I'm not exactly sure if this the correct way to implement it, but my idea was to give a redirection to a successful (or unsuccessful) submission with a response code.

Let's say in this situation we are doing an update to an existing blog post.

First, we'll check if the record exist? Ideally, I would like to stay on the current page (w/ a response code) if it doesn't.

$blogpost = Blogpost::find($id);
if(is_null($blogpost)){
    return response()->json(["message"=>"Record Not Found!"], 404);
}

Secondly, I would do a validation check to see if everything is okay. To which we would also like to stay on the current page (w/ a response code) if it's not correct.

$valid=['title' => 'required|min:3',
        'msg'=>'required|min:3',
];

$valida = Validator::make($request->all(), $valid);
if($valida->fails()){return response()->json($valida->errors(), 400);}

Lastly, when all goes I would like to have a redirection (with a 200 response code).

$blogpost->update($request->all());
return redirect('/blogposts')->with('success', 'Post Has Been Updated!');

But the goal is to have both a redirection with a response code. So, what I thought of doing was the following which isn't correct I think.

return redirect('/blogposts')->with(response()->json($blogpost, 200));

Hopefully, someone could provide me with some guidance thank you in advance!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire