In Laravel, even though it is possible to make queries to the database using a SQL-like syntax, there is a better alternative and that is to use Laravel’s ORM, Eloquent.

For those who don’t know, an object-relational mapper or ORM is a “library” that automates the interaction with the database, switching the data structure from a schema – or table – into an object1Full Stack Python. Object-relational Mappers (ORMs). In this case, Eloquent is the ORM Laravel has by default.

It is not a bad practice to use a SQL-like syntax in Laravel to make the queries, but, using Eloquent can speed up the process, avoid syntax errors, security flaws and it provides a more readable code.

All of the following Eloquent’s methods can be found also on Laravel’s official documentation2Laravel. Eloquent: Getting Started. Here I’ll show what I’ve used the most over time.

📍 Find one specific element

$book = t_book::where("book_id", $idBook)->first();

This way is not technically wrong, but, there is another statement we can use that is significantly more clear to read and write.

$book = t_book::find($idBook);

With find we get the specified element as the only result.

📍 Counting elements

$books = DB::table('t_book')->select(DB::raw('count(*) AS books'))->get();

Again, that’s a way to do it, but Eloquent already provides a count expression. On the other side, the raw statement has more potential when we need to use directly the query builder3Laravel. Database: Query Builder.

$books = t_book::count();

📍 All elements

If you required all the elements of the schema without any filter, the statement all is the fastest way to get it done.

$books = t_book::all();

📍 Getting only the values

$books = t_book::orderBy('name','asc')->pluck('name', 'book_id');

This particular function only returns the values, not the column names with the values as an object, this function is extremely useful to fill a select input on the front-end.

📍 Get only the first element

$books = t_book::orderBy('name','asc')->get();
$book = $books[0];

It does the task, but if the intention is to get only the first element, the first statement is more suitable.

$book = t_book::orderBy('name','asc')->first();

📍 Update a single element as an object

    'name' => $newName,
    'author' => $newAuthor,

Although this syntax is both correct and acceptable, there is another way – a faster one – to get the same task done.

$book->name = $newName;
$book->author = $newAuthor;

Both options are correct, but the update statement makes more sense when it is a massive update, for updating a single element, the second way is faster.

Laravel is a powerful technology that takes time to dominate, for more information about Eloquent’s functionalities and query builder check out the references down below.

References   [ + ]