laravel eloquent orm ->

eloquent

laravel makes interacting with databses extremely simple across a variety of supported databases using 

raw sql, a fluent query builder adn eloquent orm

orm abbreation -.> object relationship model


db facade provide methods for each type of query: select ,update,insert, delete and statement

try{}

catch{}


catch(\Exception $ex){

return $ex->getMessage();

}

db:select(select * from custoemrs)


toSql();

session()->flash('success','userdata inserted succesfully');

eloquent

orm object relation mapper

orm that makes it enjoyable to interact with ur databse

each database table has a corresponding model that is used to interact witht that table

eloquent models allow uou to insert,update,select,retrieve,delete records from table


php artisan make:model testmodel --mcr(model controller table)


ProductCar

product_cars plural form snake case genreted in this version table

in a table we have one column that is primary key , that one we have to mention that in  model otherwise id as primary key

MCR MODEL.PHP

protected $primaryKey='mcr_key';

public $incrimenting =false;

protected  $incrimenting =false;

protected $keyType = 'string';

public const CREATED_AT = 'new_created_at';

public const UPDATED_AT = 'new_updated_at';

protected $conection = 'sqlite';

protected $attirbutes = ['car_type',='sedan',];

protected $fillable = ['user_id','car_type','contact'];


one to one

one to many

many to many

has one

has many

one ot one polymorphic relation ship

one to many polymorphic relation ship

many to many polymorphic relation ship



one to one

users and orders table

customer place order

left join -> 

query builder -> pagination



hasone belongsto
\
in our company we habe so many brands and dealer
one brand one dealer

it is caled one to one relation ship

php artisan make:model dealer -all


model,controller,migration.,seders,factoreis,request class,policy 

brand , dealers

brand.php
has one delears

dealer.php
belongsto brand

ist created a brand, after that one delar assign brand
brand has hasone
delare has belongsto


brand.php
dealers table has brand id


dealers belong to brand









to array
brand with dealer hasone



delaer with brand 
one delaer  or belongs to which brand



d
brand,php
brand hs id that equals to dealr brand id
local key is last
foreight keyn is second one
clas is ist one






one to many relations ships

one brand can supply by one delear or so many dealers





many to many relation ships

one brand has one dealer
one brand has many deleares
one dealer hsa many brands


skoda is a brand
skoda has ahmedabad,hyd,delhi dealers
and 
delhi dealer has skoda,tata,suzuki brands

for this we will make one table in betwee, we store brand and delears id


in dealrs.php
belongstomany


brand_Dealers table with brand id and dealr id









laravel has one through relation

one to one relation with another model
this relation indicates that the declaring model can be matched with one istance of another model by proceeeding through a third model

erm between two models

countries,states,cities
countries
state has country id
city has state id

join three tables or

countries.php model
protected $table ='countries';
public function cities()
{
 return $this-> hasonethrough(
    city::class,
state:class,
'country_id',
'state_id',
'id',
'id'


);
}
states.id=cities.state_id







state.php
protected $table ='state';

city.php
protected $table ='city';


controller
$citie4s = new stdCLass90;
$countries= country::get();
if(isset($request->country))
{
$cities = country::where('id',$request->country)->with('cities')->get()->toArray();










array in a beautifull way


has many through relations ships

convineint way to access data 
coutry state cities
so many cities for one state , in above it showing one city



has many through relation ship provides a  convenient way to access distant relations via an intermediate role


"countries.id = states.country_id",
"states.id = cities.state_id"





You can define the following relationships in your model classes:

php
class Country extends Model { public function states() { return $this->hasMany(State::class); } public function districts() { return $this->hasManyThrough(District::class, State::class); } public function cities() { return $this->hasManyThrough(City::class, District::class); } } class State extends Model { public function country() { return $this->belongsTo(Country::class); } public function districts() { return $this->hasMany(District::class); } public function cities() { return $this->hasManyThrough(City::class, District::class); } } class District extends Model { public function state() { return $this->belongsTo(State::class); } public function cities() { return $this->hasMany(City::class); } } class City extends Model { public function district() { return $this->belongsTo(District::class); } }

class Country extends Model { public function states() { return $this->hasMany(State::class); } public function districts() { return $this->hasManyThrough(District::class, State::class); } public function cities() { return $this->hasManyThrough(City::class, District::class); } } class State extends Model { public function country() { return $this->belongsTo(Country::class); } public function districts() { return $this->hasMany(District::class); } public function cities() { return $this->hasManyThrough(City::class, District::class); } } class District extends Model { public function state() { return $this->belongsTo(State::class); } public function cities() { return $this->hasMany(City::class); } } class City extends Model { public function district() { return $this->belongsTo(District::class); } }


With these relationships defined, you can retrieve related models for a given country like this:

php
$country = Country::find($countryId); $states = $country->states; $districts = $country->districts; $cities = $country->cities;

$country = Country::find($countryId); $states = $country->states; $districts = $country->districts; $cities = $country->cities;


$state = State::with('districts.cities')->find($stateId);

$country = Country::with('states.districts.cities')->find($countryId);


Similarly, to retrieve related models for a given state, district, or city, you can use the appropriate relationship method on the corresponding model object.

one to one polymorphic relation ship


carfactory.php



ccustomerfactory .php





$table->morphs('column_name') is a shortcut, it will create 2 columns:

column_name_id with unsigned integer datatype and

column_name_type with string datatype to create polymorphic relationship

so

$table->morphs('taggable');

is the same as:

$table->unsignedInteger("taggable_id");
$table->string("taggable_type");



imagefactory.php








cars.php


car::with('image')->first()->toarray();;




cars with image

customer.php


$customer=customer::with('image)->first)->toarray();

print_r([$cars,$customres])







above one toone polymorpghic relation tellls
one image table for all tables like custoemr ,cars






laravel eloquent orm one to many polymorphic relation ship


car has many images 
customer has many images







many to many polymorpghic



car has so many tags and that has tag id
customer hs tags and it has tag id









taggable model
taggables migration




tags migration



image.php




tag.php





customer.php



taggable seeder







car has customer , customer has tag





laravel eloquent orm accessors

an accessor transforms an eloquent attribute value when it is accessd

to define an accesor create a get attribute on ur model where attibute is the studly cased name of hte column u wish to success




writing automatic functions on model

In Laravel, an accessor is a method defined on a model that allows you to retrieve an attribute value from the model and manipulate or format it before returning it to the caller.

For example, let's say you have a "User" model with an "email" attribute. You can define an accessor method called "getEmailAttribute()" that will automatically be called when you try to access the "email" attribute on the model. This allows you to format or modify the value of the "email" attribute before it is returned.

Here's an example of how you might define an accessor in a Laravel model:

php
class User extends Model 
{
public function getEmailAttribute($value
{ return strtolower($value); // format email address to be lowercase
}

Now, whenever you access the "email" attribute on a User model instance, Laravel will automatically call the getEmailAttribute() method to get the value of the attribute, and the returned value will be the lowercase version of the email address.

You can use accessors to manipulate or format any attribute on a model, not just the "email" attribute. This can be useful for things like formatting dates, adding prefixes or suffixes to values, or manipulating data in other ways before it is returned.

user.php

get, and curlu bracksts

it s a function when calls this user model, it will print in combinaiton





laravel orm mutators


before saving to database, modify the value


In Laravel, mutators are special methods defined in an Eloquent model that allow you to modify the value of a model attribute before it is saved to the database, or retrieve it in a modified form after it is retrieved from the database.

Here's an example of a mutator that formats a phone number attribute:

php
class User extends Model { /** * Set the user's phone number in a formatted manner * * @param string $value * @return void */ 
public function setPhoneNumberAttribute($value
{ $this->attributes['phone_number'] = preg_replace('/[^0-9]/', '', $value); } /** * Get the user's phone number in a formatted manner * * @param string $value * @return string */ public function getPhoneNumberAttribute($value
{ return substr($value, 0, 3) . '-' . substr($value, 3, 3) . '-' . substr($value, 6); } }

In the example above, we define two mutators: setPhoneNumberAttribute and getPhoneNumberAttribute.

The setPhoneNumberAttribute method receives the raw value of the phone_number attribute as an argument, and it uses a regular expression to remove any non-numeric characters from the value before it is stored in the database.

The getPhoneNumberAttribute method is called when retrieving the phone_number attribute from the database. It takes the raw value from the database as an argument, and it returns the formatted phone number, adding hyphens to separate the area code and the local number.

By defining these mutators in the User model, we can ensure that the phone_number attribute is always stored and retrieved in the format we want, without having to modify the value in every controller or view where it is used.


  1. ORM stands for __________.

    Marked Answer : object-relation mapper

    Correct Answer : object-relational mapper

  2. Which property is used to specify model's primary key?

    Marked Answer : $primaryKey

    Correct Answer : $primaryKey

  3. Which property is used to specify model's database connection?

    Marked Answer : $database

    Correct Answer : $connection

  4. Which method is used to determine one to one relationship?

    Marked Answer : hasOne()

    Correct Answer : hasOne()

  5. Which method is used to define many to many relationship?

    Marked Answer : manyToMany()

    Correct Answer : belongsToMany()

  6. An ______ transforms an Eloquent attribute value when it is accessed.

    Marked Answer : Accessor

    Correct Answer : Accessor

  7. To define a _____, define a set{Attribute}Attribute method.

    Marked Answer : Mutator

    Correct Answer : Mutator






















































No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...