logo

Laravel tips and tricks - part 2

Laravel tips and tricks - part 2

This article is the 2nd part of this topic ( Laravel tips and tricks ). If you want to read the first part you can click here and read this.



1. Select columns as an alias

If you want to make your query more readable with a relative column name (Sometimes you may need it to understand easily ) you can use MySQL 'as' keyword like this

$users = DB::table('users')->select('nid as national_id')->get();



2. Change model default fields

If your table not created from migration or not as structured as laravel rules you may need to change some default options/fields of laravel models. Like if your product table has the primary id field named 'product_id' then you need to override your primary id in the model to use laravel model class.


<?php


namespace App\Models;


use Illuminate\Database\Eloquent\Model;


class Product extends Model

{

 protected $primaryKey = 'product_id';

}


if your table does not contain the timestamps fields created_at and updated at you can also specify it like this

public $timestamps = false;


you can also define your table name manually if your table name is not fit as laravel convention like this

protected $table = 'table_product';



3. Quick orderBy tips

If you need to order your query result by created_at (as well as it would be the same result for id) generally we can query it for descending order like


$products = Product::orderBy('created_at', 'desc')->get();


You can query it in a shorter way like:

$products = Product::latest()->get();


For query ascending order, you can query like this

$products = Product::oldest()->get();


The latest() and oldest() method order by the result depending on the created_at column or your table.



4. Getting multiple results by the find() method

Generally, to retrieve row by primary key we can use the find() method like this

$product = Product::find($id)


We can retrieve multiple rows by using the find() method like this

$product = Product::find([1, 3, 9]) // primary keys inside the array



5. Hide columns

If you want to hide some columns you can do it by the makeHidden() method. It is very useful for API.

$users = $users->makeHidden(['address', 'phone_number']);



6. Get the soft-deleted data

By default, your model class not returns the soft-deleted data. To return with soft-deleted data you can use the withTrashed() method like this

$products = Product::withTrashed()->get();


If you are using query builder soft-deleted data will be retrieved automatically. like

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



7. Count related models

If you want to count the result of your relation models you can do it by withCount() method instead of with() method. Like if you want to retrieve users with posts you can query the relationship like this

$users = User::withCount('posts')->get();


The withCount method will place a {relation}_count attribute on the resulting models. like:

foreach ($users as $user) {

 echo $user->posts_count; // return users post count

}



8. Constraining Eager Loads

If you need to filter your relationship you can do it by passing an array of relationships to the with method where the array key is a relationship name and the array value is a closure that adds additional constraints to the eager loading query.


$users = User::with(['posts' => function ($query) {

 $query->where('title', 'like', '%code%');

}])->get();


If you need to pass data as variable inside this array function you can pass it by use like this

$users = User::with(['posts' => function ($query) use ($category_ids) {

 $query->where('title', 'like', '%code%');

 $query->whereIn('category_id', $category_ids);

}])->get();



9. Migrate specific table

If you need to migrate a specific table only you can add the path flag to your migration command. like:

php artisan migrate --path=/database/migrations/migration_file.php



If you learn something new from this article and know more tips and tricks share it article.

At 18th Apr 2023
Share Content:
Read: 12

Recent Comments