Laravel API vs Web Validation Errors: How Does It Work?

Laravel API vs Web Validation Errors: How Does It Work?

Laravel Daily

2 года назад

20,840 Просмотров

Ссылки и html тэги не поддерживаются


Комментарии:

Al Nahian
Al Nahian - 06.04.2023 13:08

Hahah! Glad that I found this video. I was maniacally using `try-catch` block and using FormRequest classes at the same time until chatGPT told me that I'm a jerk and I should stop bloating my controllers with unnecessary try-catch blocks 😄😄

So my code was :

```
try {
Project::create($request->validated());
} catch (\Throwable $th) {
return back()->withErrors($request);
} finally {
return to_route('projects.index'); // later I realised I don't even need the `finally` statement too.
}
```

then I refactored it to:
```
Project::create($request->validated());
return redirect()->route('projects.index');
```

Ответить
Ahmed Jaber
Ahmed Jaber - 06.03.2023 18:12

Thanks for the informations,
PostMan tip:
click on collection, add this script to "pre-request script" tab (you don't need to set headers for each new request tab)
--------------------------------
pm.request.headers.add({
key: 'Accept',
value: 'application/json'
});

pm.request.headers.add({
key: 'Content-Type',
value: 'application/json'
});

Ответить
Pyae Sone
Pyae Sone - 29.08.2022 14:00

Thz a million, u made my day sir😙

Ответить
Bass Thanaphol
Bass Thanaphol - 24.07.2022 17:05

Thank you.

Ответить
Marko Perica
Marko Perica - 23.07.2022 18:09

Thank you! This is just what I was searching for.

Ответить
Arthur Ramires
Arthur Ramires - 14.07.2022 03:15

Thank you very much, you helped me a lot.

Ответить
Muazan Qureshi
Muazan Qureshi - 06.07.2022 14:20

Thanks that solve my problem 😊😊

Ответить
sokeng vorn
sokeng vorn - 15.05.2022 07:52

I love your videos.😍

Ответить
Alex Markov
Alex Markov - 21.04.2022 15:27

It is solution for me, thanks

Ответить
Glowie
Glowie - 03.03.2022 18:49

the request must add the correct accept header lol

Ответить
Sports And Study
Sports And Study - 03.02.2022 08:46

One thing i find in Api response is that you enter price as a integer then why response in string please..

Ответить
Ali Awwad
Ali Awwad - 01.02.2022 22:00

Thank you, the "Accept application/json" did the trick.

Ответить
Razvan Zamfir
Razvan Zamfir - 15.01.2022 01:01

My Postman does not allow me to change the value for "Accept" to application/JSON . It is locked.

Ответить
Victor Clima
Victor Clima - 04.10.2021 22:06

thanks, very helpful

Ответить
Sumit Saini
Sumit Saini - 28.08.2021 21:57

At the end you skip to concatenate the rules to upper rules
Example
$rules = [
"name"=>'required',
"description"=>'required',
"price"=>'required',
]
$rules += [
"device_name"=>'required'
]
If you $this->wantsJson() condition true on that time only device_name rules validate other rules like name and description are skip because you skip to concatenate with existing rules

Ответить
Ярослав Шиковец
Ярослав Шиковец - 25.08.2021 18:09

Love your videos ❤️

Ответить
JohnnyBigodes
JohnnyBigodes - 25.08.2021 09:32

For API responses I use a dedicated middleware that checks for the headers and take a look if the requested json is also valid. There were many times people were using invalid json, forgetting to put a comma or putting a comma after the last field. Not everyone uses Postman or insomnia that shows that before requesting.

Ответить
Данил Кравцив
Данил Кравцив - 25.08.2021 05:55

Hello, I have a question, not in that theme, but.
Is there any way to set belongstothrough relation in the laravel?

Ответить
Carlos Carucce
Carlos Carucce - 24.08.2021 20:38

As simple as that... Thank you!

Ответить
Andres Martinez
Andres Martinez - 24.08.2021 20:13

Started with Laravel a couple of weeks ago, and im learning a lot with your channel, thx for all the effort you put in your videos.

Ответить
Giovani Souza
Giovani Souza - 24.08.2021 19:13

Wonderful!

Ответить
FitBouncer
FitBouncer - 24.08.2021 18:23

Can you give you "how to create api" course free? Coz I've not enough money to buy but I need to learn, please, give me any coupon

Ответить
Giacomo Garavaglia
Giacomo Garavaglia - 24.08.2021 18:20

happened to me 2 hrs ago!

Ответить
Ajay Kumar
Ajay Kumar - 24.08.2021 17:45

What if in web we have email and in API we have email_address is conditional checking is good for this?

Ответить
Abdul Rehman
Abdul Rehman - 24.08.2021 15:50

I just add a custom middleware that forces the API routes to always expect json and thus return json response.

Ответить
That's Enam
That's Enam - 24.08.2021 14:55

What if i want to customize the error response style of json part??

Ответить
haroldpepete
haroldpepete - 24.08.2021 14:47

great, thank for take your time and respond me, best regard

Ответить
Francis Sebin
Francis Sebin - 24.08.2021 14:33

Is this will give exact error instead of home page in postman without giving application/json in postman header?

Ответить
Chim
Chim - 24.08.2021 13:34

As always, excellent content.

I would recommend anything done via an API client should always use the Accept Application/Json header.

Ответить
Stoney_Eagle
Stoney_Eagle - 24.08.2021 12:01

This is why i love laravel, it's all so easy to make it do what you want.

Ответить
Muhammed Sarı
Muhammed Sarı - 24.08.2021 11:25

I use an "AcceptsJson" middleware in my API middleware group to force Laravel to render as JSON at any given time. Even if the client does not explicitly request it, because it does make absolutely no sense to return HTML from an API route.

Just a simple $request->headers->set('Accept', 'application/json'); et voilà.

Ответить
ShoeMoney
ShoeMoney - 24.08.2021 11:22

expects json is one of those that you dont think its needed or done know about it until you do...... then you never forget.

Ответить
Alex Averkiyev
Alex Averkiyev - 24.08.2021 11:18

Great hint.
In the end you mistyped. Should be $rules['device_name'] = 'required'; Otherwise it adds a '0' key to $rules with value of array.

Ответить
Jakub Stephan
Jakub Stephan - 24.08.2021 11:03

Nice video again! Are you going to be back to making public code review and publish as video here ? :)

Ответить
Hakan
Hakan - 24.08.2021 10:47

Thank you for your very helpful daily videos! Few questions comes from me, how I can define resources like you did for products? Where these resources stored on? I saw this resource thing in cloudcreativity/laravel-json-api and as far as I guess, if I define a resource, Laravel will automatically define some routes like list products (get), create product (post), show product (get), update product (patch), delete product (delete), and I will be able to use these routes in my API without writing controllers for each of them. Am I correct? This is the way in laravel-json-api and I found it awesome. Thanks in advance!

Ответить
Serdar Myradov
Serdar Myradov - 24.08.2021 10:17

thank you. With this video. I got an answer to my comment too

Ответить
Edo Khudeeda
Edo Khudeeda - 24.08.2021 09:53

Big thanks

Ответить
atique chowdhury
atique chowdhury - 24.08.2021 09:45

I'm gonna throw a few more questions your way since I like the current line of topics you are covering. Great Job and Thanks a Lot. Helps us little guys out a lot.

1. So say I have a validation for store method that accepts an image along with some other data (e.g name and email). Should look like this:
$request->validate([
'name' => ['required', 'string', 'min:3', 'max:255'],
'email => ['required', 'string', 'min:3', 'max:255'],
'image' => ['required', 'image', 'max:3000'],

]);
But I won't allow the the user to update the image after store. It is a one time thing only. So the validation in update method looks like this:
$request->validate([
'name' => ['required', 'string', 'min:3', 'max:255'],
'email => ['required', 'string', 'min:3', 'max:255'],

]);
Should I make 2 separate request classes or is there an easier way to handle this with a single request class ??

2. So I have a registration that, alongside some other rules, will check for a unique e-mail address in the database like this:
$request->validate([

'email => ['required', 'string', 'min:3', 'max:255', 'unique:users,email_address'],

]);

But say (with a grain of salt. This is just an example) I will no longer validate email asunique in the update method. Maybe because I am allowing duplicate e-mails for multiple accounts owned by the same person(say I can somehow check that and approve). So my update method validation looks like this:
$request->validate([
'email => ['required', 'string', 'min:3', 'max:255'],

]);
So basically my store method email validation has one extra rule(unique).
Again, do I need to make 2 separate request classes or can I somehow use one single request class to accomplish this ?

Ответить
Gergely Csermely
Gergely Csermely - 24.08.2021 09:44

Thanks for the nice demo with the Json format check. Really Interesting
With the new Validation Rule: Rule::when($this->wantsJson(), ['required', '']) we could add this too

Ответить
William
William - 24.08.2021 09:30

Your video came at the perfect time. I am testing an api and all the responses are html so far. I know what to do now.

Ответить
Joseph Emeruwa
Joseph Emeruwa - 24.08.2021 09:27

Amazing video. 🙌🏼

Please can you do something on Elastic Search

Ответить
Akshay kumar ojha
Akshay kumar ojha - 24.08.2021 09:14

Indeed great tutorial, Thank you so much for share amazing videos

Ответить
AL IMRAN SUJON
AL IMRAN SUJON - 24.08.2021 09:05

Great video

Ответить
Brian Chen
Brian Chen - 24.08.2021 08:36

Amazing !! What a pretty code

Ответить
Tamim Ikbal
Tamim Ikbal - 24.08.2021 08:17

You are a superb person, as always. Now, I feel that I follow a great person 😍😍😍😍😍😍

Ответить
Vitor Fontoura
Vitor Fontoura - 24.08.2021 08:15

At the end of the video, the rule does work that way or should it actually be $rules['device_name'] = 'required' ? Anyway, nice tip, thanks for the videos.

Ответить
Learn with Faisal
Learn with Faisal - 24.08.2021 08:09

Always Learning from your video. <3

Ответить