Top 4 Laravel Tips and Tricks

PHP Laravel Framework is one of the most popular web frameworks nowadays. In this article, we will share some of the top Laravel tips and tricks with you.

#Laravel Tips 1 – Push Method

Instead of saving all relationships separately, you can save all the relationships in a single line code. Save the model and all of its relationships at once using the push method.

Laravel tips and tricks :  Push Method
/**
 * Save the model and all of its relationships.
 *
 * @return bool
 */
public function push()
{
    if ( ! $this->save()) return false;

    // To sync all of the relationships to the database, we will simply spin through
    // the relationships and save each model via this "push" method, which allows
    // us to recurse into all of these nested relations for the model instance.

    foreach ($this->relations as $models)
    {
        foreach (Collection::make($models) as $model)
        {
            if ( ! $model->push()) return false;
        }
    }

    return true;
}

It just shows that push() will update all the models related to the model, so if you change any of the relationships, then call push() It will update that model and all its relations.

$user = User::find(32);
$user->name = "TestUser";
$user->state = "Texas";
$user->location->address = "123 test address"; //This line is a pre-defined relationship
// Save all the data into User and Address model.
$user->push();

It will save all the data, and also save the address into the address table/model, because you defined that relationship in the User model.

push() will also update all the updated_at timestamps of all related models of whatever user/model you push().

You can read more about laravel eloquent relationships from this doc.

#Laravel Framework Tips 2 – getOriginal and getRawOriginal Method

The getRawOriginal method will actually grab the value from the $original array.

#3 – foreignIdFor Method

Basically, it creates a foreign key based on the class’s snake case appended by the primary key column.

#4 – Route Helper Function

By default, the route function is returning an absolute path, the full URL. If you pass in false, you only get the path back. This can be useful if you want to pass the URL to your frontend or if you want to display the URL in your application without the domain.

Leave a Comment

Your email address will not be published. Required fields are marked *