Query-builder-in-laravel
notes for some essential query builder methods.
we will use users and posts table for applying q-builder methods
user table :
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
post table:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->foreignId('user_id')->constrained('users')->cascadeOnDelete();
$table->string('slug')->nullable();
$table->text('excerpt')->nullable();
$table->longText('description')->nullable();
$table->boolean('is_published')->default(false);
$table->integer('min_to_read')->nullable();
$table->timestamps();
});
Now we will link up user and post model for one to many relationship with these methods in Models/User.php file and Models/Post.php file
User Model :
public function post():HasMany{
//here one user has many post
return $this->hasMany(Post::class) ;
}
//accessing post data from user
$user_table_instance->post()->post_table_column_data
Post Model :
public function user(){
// one post belongs to one user
return $this->belongsTo(User::class) ;
}
//accessing user data from post
$post_table_instance->user()->user_table_column_data
Now its time to seed or insert some data manually in users and posts table.
After these , we are ready to use methods of query builder
Codes from in PostController.php
//here we grab table named "posts" and tell return me
//all data of posts table
$posts = DB::table('posts')->get() ;
//After targeting 'posts' table we select
//a column named 'title' in 'posts' table
// and get all data of 'posts' table these query
//will return us posts table all data with 'title' columns only
$posts = DB::table('posts')->select('title')->get() ;
//another example for select method these query will return
//us all 'posts' table data
// with column name 'title' and 'excerpt'
$posts = DB::table('posts')->select('title','excerpt')->get() ;
//these query will return same data as previous query
// the difference between this and previous query is
// we must read 'excerpt' values with modified name 'ex'
$posts = DB::table('posts')->select('title','excerpt as ex')->get() ;
//these will return the unique or distinct values
//of 'is_published' column of 'posts' table
//please dd to observe output
$posts = DB::table('posts')->select('is_published')->distinct()->get() ;
//return all data of 'posts' table with 'title' and 'is_published'
//values
$example = DB::table('posts')->select('title','is_published')->get();
//this query will return same results
$posts = DB::table('posts')->select('is_published');
$example = $posts->addSelect('title')->get() ;
dd($example) ;
//this query will return a array of 'posts' table row/element
//where value of id column is equal to 2
//->get() method return data as array
//where is a method that check the condition and pass
// responsibility to next chained method , here get()
// where('column_name','to be searched value') it works like
// if('column_name' == 'to be searched value')
// return matched data
//else
//return null value
$posts = DB::table('posts')->where('id',2)->get();
//another method example named ->first()
//first method will return checked and matched data
//as a object
$posts = DB::table('posts')->where('id',2)->first();
//in this query where() method will check condition is ok
//or not if not then $posts will be null, if condition inside
//where method is true then it will return row values
//with id=2 now chained method value() almost similar to select
//method,value('title') will return title column value only.
//difference between select() and value() is select can return
//more then one column data and value() can return single column
//data only
$posts = DB::table('posts')->where('id',2)->value('title');
//this query will return a row data matched with id 2
//return type will be object
$posts = DB::table('posts')->find(id:2);
previous queries was something like , at first we select a row data of
'posts' table then we retrieving column data from our targeted row.
'posts_table'->'targeted_row'->'column_value_of_targeted_row'
here is a query method named pluck() ,we can use this method all column
data of "posts" table.
'posts_table'->'targeted_column_values'
//obiviously it will return all column data of
//'posts' table and return type will be 'array'
$posts = DB::table('posts')->pluck('title');
inserting data using query builder insertOrIgnore() method $posts =
$posts = DB::table('posts')->insertOrIgnore([
'id' => 1000,
'title' => 'post-title-5',
'user_id' => 2,
'slug' => 'post-slug-5',
'excerpt' => 'excerpt-5' ,
'description' => 'description-5',
'is_published' => 0,
'min_to_read' => 8
]);
dd($posts);
//this query will insert data to 'posts' table
//want to insert more then one row of data in one load then here is
//the example for insert more then one row of data
$posts = DB::table('posts')->insertOrIgnore(
[
'id' => 2000,
'title' => 'post-title-6',
'user_id' => 2,
'slug' => 'post-slug-6',
'excerpt' => 'excerpt-6' ,
'description' => 'description-6',
'is_published' => 1,
'min_to_read' => 8
],
[
'id' => 3000,
'title' => 'post-title-7',
'user_id' => 3,
'slug' => 'post-slug-7',
'excerpt' => 'excerpt-7' ,
'description' => 'description-7',
'is_published' => 1,
'min_to_read' => 8
]
);
dd($posts);
now here is upsert() method to insert data in 'posts' table , or update data in 'posts' table
upsert() method accepts two arguments one is 'updated_data' another is 'array of column name' array element may be one or more...
it works like , at first upsert() method search in 'posts' table respect to accepted second argument [array of column name] , if upsert method find or
can matched a record with [array of column name] then upsert method update the targeted data with accepted first argument data.
if upsert method can not find or matched record in 'posts' table then
it will create a new record in 'posts' table with accepted first argument data
finally upsert method first argument data is real data should be inserted or updated , second argument data is for condition checking
$posts = DB::table('posts')->upsert([
'id' => 2000,
'title' => 'post-title-6-updated',
'user_id' => 2,
'slug' => 'post-slug-6-updated',
'excerpt' => 'excerpt-6-updated' ,
'description' => 'description-6-uu',
'is_published' => 1,
'min_to_read' => 88
],['title','slug']);
dd($posts) ;
insertGetId() method will create a record and will return the created id number of new record in 'posts' table
$posts = DB::table('posts')->insertGetId([
'id' => 8000,
'title' => 'post-title-88',
'user_id' => 2,
'slug' => 'post-slug-99',
'excerpt' => 'excerpt-99' ,
'description' => 'description-99',
'is_published' => 1,
'min_to_read' => 22
],['title','slug']);
dd($posts) ;
analyse these example code yourself for better understanding
you should be capable enough to understand these codes below
$posts = DB::table('posts')
->where('id', '=', 1000)
->update([
'title' => 'updated-title-uu-equal-contion'
]);
$posts = DB::table('posts')
->where('id', '<=', 2)
->update([
'title' => 'updated-title-uu-less-then-condition'
]);
$posts = DB::table('posts')
->where('id', '>=', 3)
->update([
'title' => 'updated-title-uu-grater-then-condition'
]);
dd($posts);
now it time to delete record from 'posts' table
$posts = DB::table('posts')->where('id',3000)->delete() ;
dd($posts) ;
aggregates methods highly useful method in q-builder
//this count() method will return the number of records in
//table
$posts = DB::table('posts')->count() ;
//this will return the number of is_published true record
$posts = DB::table('posts')->where('is_published',1)->count() ;
//will return sum of 'min_to_read' columns in 'posts' table
$posts = DB::table('posts')->sum('min_to_read') ;
$posts = DB::table('posts')->avg('min_to_read') ;
//filtering is_published true only
$posts = DB::table('posts')->where('is_published',true)->avg('min_to_read') ;
$posts = DB::table('posts')->max('min_to_read') ;
//min method will ignore null values
$posts = DB::table('posts')->min('min_to_read') ;
dd($posts) ;
//this query will return all records without matched recode
//inside whereNot() conditional record
$posts = DB::table('posts')->whereNot('id',2)->get() ;
//this is will return records with id grater then
//or equal to 2
$posts = DB::table('posts')
->whereNot('id', '<=' ,2)
->get() ;
//this will return "is_published" : false records
$posts = DB::table('posts')
->orWhereNot('is_published',true)
->get() ;
//this will return a boolean value , true or false
//based on condition
$posts = DB::table('posts')->where('id',22)->exists() ;
//this will return records contain id between condition
// inclusive result
$posts = DB::table('posts')->whereBetween('id',[3,2000])->get() ;
//this returend result will be inverse of whereBetween
$posts = DB::table('posts')->whereNotBetween('id',[3,2000])->get() ;
that's all for basic uses of query builder methods.
this post may be update later with more essential methods and
examples , thank you.