CoderFunda
  • Home
  • About us
    • Contact Us
    • Disclaimer
    • Privacy Policy
    • About us
  • Home
  • Php
  • HTML
  • CSS
  • JavaScript
    • JavaScript
    • Jquery
    • JqueryUI
    • Stock
  • SQL
  • Vue.Js
  • Python
  • Wordpress
  • C++
    • C++
    • C
  • Laravel
    • Laravel
      • Overview
      • Namespaces
      • Middleware
      • Routing
      • Configuration
      • Application Structure
      • Installation
    • Overview
  • DBMS
    • DBMS
      • PL/SQL
      • SQLite
      • MongoDB
      • Cassandra
      • MySQL
      • Oracle
      • CouchDB
      • Neo4j
      • DB2
      • Quiz
    • Overview
  • Entertainment
    • TV Series Update
    • Movie Review
    • Movie Review
  • More
    • Vue. Js
    • Php Question
    • Php Interview Question
    • Laravel Interview Question
    • SQL Interview Question
    • IAS Interview Question
    • PCS Interview Question
    • Technology
    • Other

10 December, 2020

Laravel Query Builder & Eloquent ORM

 Programing Coderfunda     December 10, 2020     Laravel     No comments   

 An application always needs to interact with a database and Laravel makes this task hassle free. Few tools that make Laravel an awesome framework is the inclusion of “Query Builder and Eloquent ORM”. Through this blog I intend to share few quick pointers on these concepts.

 Query Builder:

In LaravelLaravel the database query builder provides an easy way to create and run database queries. It can be used to perform all the database operations in your application, from basic DB Connection, CRUD, Aggregates etc and it works on all supported database systems like a champ.

 The notable factor about query builder is that, since it uses the PHP Data Objects (PDO), we need not worry about SQL injection attacks (Make sure we don’t inadvertently remove this protection). We can avoid all those lines of code to sanitise the data before feeding it to the DB.

 So, how do we create a simple select query to fetch all values from the users table?

1
$users = DB::table('users')->get();

 DB::table is responsible to begin a fluent query against a database table. The table from which the value has to be selected is mentioned inside the brackets within quotes and finally the get() method gets the values. Similarly to fetch a single row we can modify the above code by adding a where clause

1
$user = DB::table('users')->where('name', 'shivam')->first();

Here, we are trying to fetch a row that has the value Shivam in its name column. The first() method will only return the first find. What if we need only the user id of Shivam. Instead of returning the entire result array we can simply pluck out that specific column?

1
$user_id = DB::table('users')->where('name', 'shivam')->pluck('id');

For specifying more than one column we can use the select clause

1
$users = DB::table('users')->select('name', 'email')->get();

I now believe you are getting the grip. Things get more interesting further down.

We often write queries against certain ‘where conditions’. So how do we fetch the list of users whose user_id is less than 10?

1
$users = DB::table('users')->where(id, '<', 10)->get();

Yes, we split up the operator and the operands as three parameters and feed it to the where conditions. Now we have a situation, we need to fetch all those users whose user_id falls between 10 and 20.

1
$users = DB::table('users')->whereBetween('id', array(10, 20))->get()

Laravel has the whereBetween(), whereNotBetween(), wherein() and whereNotIn() methods to which we can pass values as an array.

Why are we passing values as an array and not as comma separated parameters?

At the start of this blog I did mention about SQL injection attacks. Let’s say that the values 10 and 20 are taken as user inputs. As programmers we cannot trust what the user types into the input field. He can be a valid user who enters proper values or someone trying to enter false values and crash your DB.

1
$users = DB::table('users')->whereBetween('id', array($from, $to))->get()

Here $from and $to are user inputs. If we look in to the Laravel’s database connection class for the select() method this array is wrapped around PDO connection and it is responsible to sanitize the data before the query is executed. So you have clean queries!!

Using Query builder we can also write raw SQL queries

1
DB::select(DB::raw(“SELECT * FROM `users` WHERE name = ‘$name’ ”));

Here $name is obtained from user input. $name may contain malicious code therefore we need to alter the above code to make it SQL friendly.

1
DB::select(DB::raw("SELECT * FROM `users` WHERE `name` = :username"),
array('username' => $name));

So the array value when passed through the PDO connection gets sanitized.

What is Eloquent in Laravel ?

Eloquent is object that is representative of your database and tables,in other words it’s act as controller between user and DBMS

For eg,

  • DB raw query,

select * from post LIMIT 1

  • Eloquent equivalent,

$post = Post::first();

$post->column_name;

What is ORM?

ORM or Object Relational Mapper is a technique to access objects without having to consider how those objects are related to their source.

What is Eloquent?

The ORM included in Laravel is called Eloquent and it enables us to work with the database objects and relationships using an expressive syntax. It is similar to working with objects in PHP. In Laravel, each database table has a corresponding “Model”. Eloquent ORM provides Active Record implementation which means that each model we create in our MVC structure corresponds to a table in our database.

Creating an Eloquent model is similar to creating a class. All the model files should be inside the app/models folder.

class Group extends Eloquent { }

All Eloquent models extends from the Eloquent class. The lower-case, plural name of the class will be used as the table name unless another name is explicitly specified. Eloquent will also assume that each table has a primary key column named “id” unless specified. We can specify a table as follows:

class Group extends Eloquent

1
2
3
4
5
{
 
protected $table = 'group_list';   // will point to group_list table if mentioned
 
}

Here, Group model will correspond to groups table (by default). We can access the data in the groups table using the basic CRUD operations.

By default Eloquent models will have auto-incrementing keys.

Create:

1
2
3
4
5
6
7
8
9
10
11
$new_group = new Group;
$new_group->name = 'NewGroup';
$new_group->description = 'Awesome Group';
$new_group->save();
<read:< pre="">
 
<strong>// To get all groups</strong>
 
Group::all();
 
// To find a group by passing the group id etc.
1
Group::find($id);

// Try to retrieve a model by primary key else throw an exception

1
2
$model = User::findOrFail(1);
$model = User::where('id', '>', 5)->firstOrFail();

Update:

// Retrieve and update

1
2
3
$group = Group::find(1);
$group->name = ‘Group01’;
$group->save();

// Using a WHERE clause

1
Group::where('name', '=', ‘Group01’)-date(array('name' => ‘Group1’));

// Delete one record

1
2
$group = Group::find(1);
$group->delete();

// Delete several

1
2
Group::destroy(1, 2, 3);
Group::where('id', '<', 10)->delete();

There are more topics to cover under Eloquent, hopefully in the next blog.

Conclusion:

It’s way of representing your database values with object you can easily use with

your application.

by: webkul.com

  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Email ThisBlogThis!Share to XShare to Facebook

Related Posts:

  • Laravel maintenance mode refresh and render parameter AnswerSorted by:                             … Read More
  • how to connect SQL server with php web application using wamp server? AnswerSorted by:                             … Read More
  • Show page numbers as navigation in Laravel pagination AnswerSorted by:                             … Read More
  • Laravel show my Posts, Followed user posts and Shared posts in a single query AnswerSorted by:                             … Read More
  • Pusher receive the data but not in the Echo callback function (laravel) 0To your Comment broadcast Class You could format your data using this function: public function broadcastWith() { return ['username… Read More
Newer Post Older Post Home

0 comments:

Post a Comment

Thanks

Meta

Popular Posts

  • Spring boot app (error: method getFirst()) failed to run at local machine, but can run on server
    The Spring boot app can run on the online server. Now, we want to replicate the same app at the local machine but the Spring boot jar file f...
  • Log activity in a Laravel app with Spatie/Laravel-Activitylog
      Requirements This package needs PHP 8.1+ and Laravel 9.0 or higher. The latest version of this package needs PHP 8.2+ and Laravel 8 or hig...
  • Laravel auth login with phone or email
          <?php     Laravel auth login with phone or email     <? php     namespace App \ Http \ Controllers \ Auth ;         use ...
  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh
    I had follow these steps to install an configure firebase to my cordova project for cloud messaging. https://medium.com/@felipepucinelli/how...
  • Vue3 :style backgroundImage not working with require
    I'm trying to migrate a Vue 2 project to Vue 3. In Vue 2 I used v-bind style as follow: In Vue 3 this doesn't work... I tried a...

Categories

  • Ajax (26)
  • Bootstrap (30)
  • DBMS (42)
  • HTML (12)
  • HTML5 (45)
  • JavaScript (10)
  • Jquery (34)
  • Jquery UI (2)
  • JqueryUI (32)
  • Laravel (1017)
  • Laravel Tutorials (23)
  • Laravel-Question (6)
  • Magento (9)
  • Magento 2 (95)
  • MariaDB (1)
  • MySql Tutorial (2)
  • PHP-Interview-Questions (3)
  • Php Question (13)
  • Python (36)
  • RDBMS (13)
  • SQL Tutorial (79)
  • Vue.js Tutorial (68)
  • Wordpress (150)
  • Wordpress Theme (3)
  • codeigniter (108)
  • oops (4)
  • php (853)

Social Media Links

  • Follow on Twitter
  • Like on Facebook
  • Subscribe on Youtube
  • Follow on Instagram

Pages

  • Home
  • Contact Us
  • Privacy Policy
  • About us

Blog Archive

  • September (100)
  • August (50)
  • July (56)
  • June (46)
  • May (59)
  • April (50)
  • March (60)
  • February (42)
  • January (53)
  • December (58)
  • November (61)
  • October (39)
  • September (36)
  • August (36)
  • July (34)
  • June (34)
  • May (36)
  • April (29)
  • March (82)
  • February (1)
  • January (8)
  • December (14)
  • November (41)
  • October (13)
  • September (5)
  • August (48)
  • July (9)
  • June (6)
  • May (119)
  • April (259)
  • March (122)
  • February (368)
  • January (33)
  • October (2)
  • July (11)
  • June (29)
  • May (25)
  • April (168)
  • March (93)
  • February (60)
  • January (28)
  • December (195)
  • November (24)
  • October (40)
  • September (55)
  • August (6)
  • July (48)
  • May (2)
  • January (2)
  • July (6)
  • June (6)
  • February (17)
  • January (69)
  • December (122)
  • November (56)
  • October (92)
  • September (76)
  • August (6)

  • Failed to install 'cordova-plugin-firebase': CordovaError: Uh oh - 9/21/2024
  • pyspark XPath Query Returns Lists Omitting Missing Values Instead of Including None - 9/20/2024
  • SQL REPL from within Python/Sqlalchemy/Psychopg2 - 9/20/2024
  • MySql Explain with Tobias Petry - 9/20/2024
  • How to combine information from different devices into one common abstract virtual disk? [closed] - 9/20/2024

Laravel News

  • Auto-translate Application Strings with Laratext - 5/16/2025
  • Simplify Factory Associations with Laravel's UseFactory Attribute - 5/13/2025
  • Improved Installation and Frontend Hooks in Laravel Echo 2.1 - 5/15/2025
  • Filter Model Attributes with Laravel's New except() Method - 5/13/2025
  • Arr::from() Method in Laravel 12.14 - 5/14/2025

Copyright © 2025 CoderFunda | Powered by Blogger
Design by Coderfunda | Blogger Theme by Coderfunda | Distributed By Coderfunda