Understanding how Relationships work in Laravel like Magic

Laravel is a trademark of Taylor Otwell. Copyright © Taylor Otwell
From the Laravel documentation, copyright Taylor Otwell
From the Laravel documentation, copyright Taylor Otwell
// We create a new model instance for the related model.
$instance = $this->newRelatedInstance($related);
/**
* Create a new model instance for a related model.
*
* @param string $class
* @return mixed
*/
protected function newRelatedInstance($class)
{
return tap(new $class, function ($instance) {
if (! $instance->getConnectionName()) {
$instance->setConnection($this->connection);
}
});
}
$foreignKey = $foreignKey ?: $this->getForeignKey();
$localKey = $localKey ?: $this->getKeyName();
$query = $instance->newQuery();
// This returns a new query builder for the Invitation class.
$parent = $this;
// This refers to the User object
$foreignKey = 'user_id';
$localKey = 'id';
WHERE phones.user_id = 1 AND phones.user_id IS NOT NULL
$phone = $user->phone;
// is the equivalent of
$phone = $user->__get('phone');
$this->getAttribute($key);
SELECT * FROM phones
WHERE phones.user_id = 1
AND phones.user_id IS NOT NULL LIMIT 1;.
  • You’re more familiar with common issues and exceptions that can occur with relationships (e.g. calling the property with () instead of accessing the magic method)
  • The tap helper function is at your disposal! It’s used a lot inside the Laravel framework and you can make use of it too, but make sure everything you make is understandable and well-documented.

Founder & CTO @ GuestFlip Connect with me: https://arispattakos.carrd.co/

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store