Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon How do firstOrFail and sole handle soft deleted records in Laravel


How do firstOrFail and sole handle soft deleted records in Laravel


In Laravel Eloquent, both `firstOrFail()` and `sole()` handle soft deleted records differently:

`firstOrFail()`

- By default, `firstOrFail()` will not return soft deleted records[1][3].
- To include soft deleted records, you need to use the `withTrashed()` method before calling `firstOrFail()`[1][5]:

php
$user = User::withTrashed()->where('email', '
 <script language='JavaScript' type='text/javascript'>
 <!--
 var prefix = 'm&#97;&#105;lt&#111;:';
 var suffix = '';
 var attribs = '';
 var path = 'hr' + 'ef' + '=';
 var addy33 = '&#101;x&#97;mpl&#101;' + '&#64;';
 addy33 = addy33 + '&#101;m&#97;&#105;l' + '&#46;' + 'c&#111;m';
 document.write( '<a ' + path + '\'' + prefix + addy33 + suffix + '\'' + attribs + '>' );
 document.write( addy33 );
 document.write( '<\/a>' );
 //-->
 </script><script language='JavaScript' type='text/javascript'>
 <!--
 document.write( '<span style=\'display: none;\'>' );
 //-->
 </script>This e-mail address is being protected from spambots. You need JavaScript enabled to view it
 <script language='JavaScript' type='text/javascript'>
 <!--
 document.write( '</' );
 document.write( 'span>' );
 //-->
 </script>')->firstOrFail();

- If no matching record is found, including soft deleted ones, `firstOrFail()` will throw a `ModelNotFoundException`[1][3].

`sole()`

- Similar to `firstOrFail()`, `sole()` will not return soft deleted records by default[1].
- To include soft deleted records, use `withTrashed()` before calling `sole()`[1][5]:

php
$user = User::withTrashed()->where('id', 1)->sole();

- If no matching record is found, `sole()` will throw a `ModelNotFoundException`[1].
- If multiple records are found, including soft deleted ones, `sole()` will throw a `MultipleRecordsFoundException`[1].

In summary, both methods exclude soft deleted records by default. To include them, use the `withTrashed()` method. If no records are found, either method will throw a `ModelNotFoundException`. Additionally, `sole()` will throw a `MultipleRecordsFoundException` if multiple records are found.

Citations:
[1] https://www.yellowduck.be/posts/the-difference-between-sole-and-firstorfail-in-laravel
[2] https://www.elegantlaravel.com/article/comparing-laravel-s-firstorfail-and-sole-methods
[3] https://dev.to/codeanddeploy/laravel-8-eloquent-query-first-and-firstorfail-example-2h44
[4] https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-query-first-and-firstorfail-example
[5] https://laravel.com/docs/5.0/eloquent