php


Laravel - replace null with empty array when no relation is found


Is it possible to replace null with an empty array when no relation is found?
E.g. The customer has contacts and contracts but one of the contract has no web.
$customers = Customer::with('contacts', 'contracts.web')
->orderBy('company')->orderBy('prename')->get();
The result would be as following...
2 => array:21 [
"id" => 1
"contacts" => array:2 [
0 => array:12 [
"id" => 1
"customer_id" => 1
]
1 => array:12 [
"id" => 2
"customer_id" => 1
]
]
"contracts" => array:2 [
0 => array:9 [
"id" => 1
"customer_id" => 1
"web" => array:7 [
"id" => 1
"contract_id" => 1
]
]
1 => array:9 [
"id" => 2
"customer_id" => 1
"web" => null // should be replaced with []
]
]
]
As I read in the docs (Constraining Eager Loads), it's only possible to manipulate the query with constraining eager loads.
UPDATE
Contract class
class Contract extends Model
{
public function web()
{
return $this->hasOne(Web::class);
}
}
For further readers here's an explanation how to solve this kind of problem.
Laravel returns an empty array if no records are found on a hasMany relation. If a hasOne relation is implemented, null will be returned.
So if you need an array also if no record is found on a hasOne relation, you need to do the following.
class Contract extends Model
{
public function web()
{
return $this->hasOne(Web::class)
->withDefault(function () {
return new Web();
});
}
}
As implemented like this its not possible to just return an empty array. Why this isn't possible, check out this issue on Laravel GitHub Issue Tracker.
There is existing code that depends on the result of any Eloquent relationship to either be null, a Model instance, or a Collection of Model instances. However, the current functionality of the withDefault() method opens up the potential for returning an object that is not one of those three expected values.
If you return a new \stdClass; or an empty array, an empty instance of web is returned. To get an empty array just instanciate a new Object of the relation class. In my case new Web();.
Your relationship method should be the one handeling this since it's the first place you can fix this
I checked this so it returns an array when the variable is null.
public class Contracts{
public function web(){
$collection = $this->hasMany('App\Web');
return $collection ? $collection : [];
}
}

Related Links

Passing a number as a string parameter
Limiting character length of output
How to add/set images on PHPOffice/PHPWord Template?
PHP - Multidimensional Array
PHP code being removed by browser
QueryFetchArrayAll from multiple tables?
Convert php arrays with the new syntax
Setting default values in php
PHP: preserving desired value in array
How to calculate rows count from left join
Check all cli processes are completed or not
PutObject into directory Amazon s3 / PHP
Creating several tables from CSV with PHP
MySQL insert or update on duplicate [closed]
php mysql last visit
Expiring URL: Code Igniter

Categories

HOME
apache-nifi
gaming
couchdb
key
systemd
visual-studio-2010
vsts-build
celery
gallery
gentelella
sharepoint-online
azure-logic-apps
hspi
mutation-testing
lc3
getopenfilename
cname
sonicwall
async-await
l20n
rpmbuild
sqlplus
el
maven-surefire-plugin
fluent-migrator
device
pdf.js
environment
fusetools
spring-annotations
delayed-job
series
riotjs
knights-tour
gnu-classpath
adminer
spring-rabbitmq
formsauthenticationticket
mv
elastica
aurelia-http-client
reset
microkernel
kitura
destroy
roracle
xcglogger
knockout-2.0
jgrapht
htmlspecialchars
google-news
android-mediarecorder
nslayoutconstraint
apache-modules
.when
openerp-6
gapi
elastic4s
multi-touch
e
xmlbeans
svnserve
nsdata
maximize
jsr363
wikimedia-commons
nette
sqlbase
hmisc
google-gdk
embeddedwebserver
angular-amd
ocmockito
nhibernate-criteria
jolie
famo.us
thoughtworks-go
utf8-decode
multivariate-testing
siena
reference-counting
rails-api
thruway
xulrunner
webaii
tabletools
cpu-time
jchartfx
map
autonumber
acitree
non-ascii-characters
jquery-transit
stty
objective-c-runtime
microformats
blobstorage
reentrancy
xalan
stretch
clrprofiler
wndproc
image-formats
opends
dropshadow
background-repeat
expression-web
play2-mini
filelock
nosetests
startupscript
kernel32
css-friendly
django-pagination
webresponse
comment-conventions
levels

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App