Laravel 9 Posts
Some Laravel tips that we must need to knowLaravel
Some Laravel tips that we must need to knowLaravel
1) Null safe operator
From PHP 8 you can use Null Safe Operator
How we are doing null checking code in PHP < 8.0
$country = null;
if ($session !== null) {
$user = $session->user;
if ($user !== null) {
$address = $user->getAddress();
if ($address !== null) {
$country = $address->country;
}
}
}
PHP 8 allows you to write this:
$country = $session?->user?->getAddress()?->country;
2) Ternary condition
We have used this ternary condition for checking null value
isset($user->image) ? $user->image : null
We can short above condition like this
$user->image ?? null
3) Clone a model
You can clone a model using replicate(). It will create a copy of the model into a new, non-existing instance.
$user = App\User::find(1);
$newUser = $user->replicate();
$newUser->save();
4) Default Relationship Models
Laravel provides a handy withDefault() method on the belongsTo relationship that will return a model object even when the relationship doesn't actually exist.
class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class)->withDefault();
}
}
Now, if we try to access the $post->user relationship, we'll still get a User object even when it does exist in the database. This is known as the "null object" pattern and helps eliminate some of those if ($post->user) conditional statements.
For more information read Laravel withDefault() doc.
5) Save models and relationships
You can save a model and its corresponding relationships using the push() method.
class User extends Model
{
public function phone()
{
return $this->hasOne('App\Phone');
}
}
$user = User::first();
$user->name = "Peter";
$user->phone->number = '1234567890';
$user->push(); // This will update both user and phone record in DB
Hope it will be helpful.
Thanks
Laravel hasOneThough & Laravel hasManyThough RelationshipsLaravel
Laravel hasOneThough & Laravel hasManyThough RelationshipsLaravel
Laravel HasOneTHough & Laravel HasManyThough Relationships
We generally know about the 4 basics Laravel Relations ships that laravel provides:
Now we are going to see the major missing relationships that we are thinking are "Hard to use", but in real cases, it's needed while developing a project.
Even though I was thinking that HasOneThough and HasManyThough Relationships were will be hard to understand, I was wrong. it's really easy to understand.
Understanding HasOneThough
Let's say there is a Library that wants to know the book issuer's name directly, in this case, we generally do :
- Fetch Books
- Fetch its related issuer by using the HasOne Relation
What if I say I can directly access the issuer name into the Library model, yes we can achieve this by using the has one though.
Library
- id
- name
Book
- id
- name
- library_id
Issuer
- id
- name
- book_id
public function issuer() {
return hasOneThough(App\Issuer, App\Book, library_id, book_id)
}
Understanding HasManyThough
Let's say in the same example that there are multiple issuers of the same books, we can achieve it as follow.
public function issuer() {
return hasManyThough(App\Issuer, App\Book, library_id, book_id)
}
Hope it will be helpful.
Thanks
UUIDs as Primary Keys with a Trait in Laravel 9Laravel
UUIDs as Primary Keys with a Trait in Laravel 9Laravel
What are UUIDs?
UUIDs stands for Universally Unique Identifiers and are 128 bits values used to uniquely identify some record in our database. UUIDs are represented as a hexadecimal string split into five groups separated by hyphens.UUIDs are universally unique alphanumeric identifiers that are 36 characters long.
Instead of using auto-incrementing integers as your Eloquent model's primary keys, you may choose to use UUIDs instead.
Updating Migration File
It is a very important step to update our migration file, I want to use the UUIDs in my User class so I will make changes to my User’s migration class.
$table->id();
to this:
$table->uuid('id')->primary();
If you are using a UUID primary key as a foreign key in another table, you need to change the column type to UUID, where the foreign key is defined. from this:
$table->unsignedBigInteger('user_id')->unsigned();
to this:
$table->uuid('user_id');
Using Trait in Our Model Class
you may use the Illuminate\Database\Eloquent\Concerns\HasUuids trait on the model.
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
use HasUuids;
// ...
}
$user = User::create(['name' => 'John','email' => 'john@doe.com']);
$user->id; //72106479-5367-4853-9b44-b8b7a1e94f01
By default, The HasUuids trait will generate "ordered" UUIDs for your models. These UUIDs are more efficient for indexed database storage because they can be sorted lexicographically.
Why use UUIDs over regular IDs?
- UUIDs are safer than using regular numeric IDs because they are not easy to spoof. Regular IDs make it easy to get information about the application, like how many users the application has.
- Using UUID is a great solution for multi-tenancy applications.
I hope you will find this post useful.