Conclusion

Laravel's ORM is powerful. In fact, there are too many types of operations to list within a single book. The simplest queries can be accomplished with a few keystrokes.

Laravel's Eloquent command gets converted into fluent commands, so if something more complicated is desired, then the fluent syntax may be used. If a very complicated query needs to be performed, then the DB::raw() function can even be used. This will allow exact strings to be used inside the query builder. Here is an example:

$users = DB::table('accommodation')
                     ->select(DB::raw('count(*) as number_of_hotels'))->get();

This returns just the number of hotels:

[{"number_of_hotels":15}]

Learning to design the software, starting with the domain and then thinking about which entities are involved in that domain, will help a developer think in an object-oriented manner. Having a list of entities leads to the creation of the table, so the actual creation of the schema will be performed last. This approach may take some getting used to. Understanding Eloquent relationships is key to being able to produce expressive, readable statements that query the database while hiding away the complexity.

Another reason why Eloquent is extremely useful is in the case of a legacy database. If the ORM is applied in a situation where the tables have nonstandard names, the keys are not named by the same name, or the column names are simply not easily understandable, Eloquent provides the developer with tools to actually help homogenize the table names and field names, and perform the relations by providing attribute getters and setters.

For example, if the field names are fname1 and fname2, we can use a get attribute function inside our model, where the syntax is get followed by the desired name to use in the application and the attribute. So, in the case of fname1, the function would be added as follows:

public function getUsernameAttribute($value)
{
  return $this->attributes['fname1'];
}

Functions such as these are Eloquent's real selling point. In this chapter, you learned how to find data inside your database by using entity models, limiting the results through the addition of where, relationships, powerful conventions such as polymorphic relationships, and auxiliary helpers such as pagination.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset