Bark at the Start ๐บ
- Woof Woof Introduction
- Birthing Pup Classes
- Eloquent Pup Conventions
- Fetching Pups
- Fetching Single Pups / Aggregates
- Boning and Playing with Pups
- Collaring Pups
- Flea-Pruning Pups
- Replicating Pups
- Pup Query Scopes
- Comparing Pups
- Life Events
Hey there, dog lover! Welcome to the Eloquent playpen, where we train our furry PHP database helpers. Sit, stay, and letโs get started! ๐พ
Welcome to the wild world of Laravel, where even databases are a blast to interact with! Meet Eloquent, our whiz-bang object-relational mapper (ORM) that turns database interfacing into a joyride. With Eloquent, each table in your database gets its own snazzy โModelโ buddy, helping you chat up the table like never before.
Oh, and donโt forget! Before we get started, remember to hook up a database connection in your applicationโs config/database.php configuration file. Need help setting up your database? Check out our Database Configuration Guide for Aliens (just kidding, itโs actually the Laravel documentation).
Now, letโs talk about generating Model classes. Itโs like creating a custom dinner jacket for each of your database tables. Simply use Laravelโs magical command line tool to whip up these posh attire items, and voila! Youโll be one step closer to being the life of every database party.
Alrighty, buckle up, because weโre about to embark on a wild journey through Laravel-landia! First stop: Modelville, population you (and your new Eloquent model). But before we set sail, letโs get our ducks in a row and ensure our models are neatly nested in the app\Models directory. Thatโs where they enjoy their posh high-living, surrounded by their illustrious peers who extend the prestigious Illuminate\Database\Eloquent\Model class.
Now, if youโre feeling a bit peckish for some fresh model code, donโt fret! You can whip one up using the trusty Artisan command (itโs like having a gourmet chef in your pocket). Give it a shout:
php artisan make:model Flight
But wait, what if youโre hankering for a side of database migration with that model? Fear not! Simply add the --migration or -m option to your command:
php artisan make:model Flight --migration
And voila! Your model and its accompanying migration are ready to hit the runway (or the database, if you will).
But why stop at just a single model? You can cook up various other types of classesโthink factories, seeders, policies, controllers, form requests, and more. Heck, you can even order them all up in one go:
php artisan make:model Flight --factory --seeder --policy --controller --request
So grab a cold brew, kick back, and let Laravelโs Artisan command do the heavy lifting for you. After all, who needs a personal assistant when youโve got a command-line wizard like this one?
Alright, buckle up, dear developer! Letโs embark on an exciting journey together. Weโre about to create a brand new model for our airline app, and itโs going to be as smooth as turbulence-free skies! ๐ฌ
First off, letโs summon the Flight model from thin air with this magical incantation:
php artisan make:model Flight --factory
Thatโs right, with just a few keystrokes and some arcane syntax, youโve now conjured up a Flight model! But wait, thereโs more! We wouldnโt want our flights to take off without proper factory settings, so letโs create a custom FlightFactory class. You can think of it as a pilotโs checklist for creating perfect flights:
php artisan make:model Flight -f
Now that weโve got our Flight model and its trusty factory companion, you can start shaping the future of air travel in your codebase. Just remember, with great power comes great responsibility (and a whole lot of fun!). Happy coding! ๐
Alrighty, buckle up, coding companions! Letโs embark on a delightful journey together through the friendly skies of Laravel land.
First stop: Modelville Airport ๐ฌ! Get ready to take off with your trusty php artisan make:model Flight --seed. This magical command will whip you up a brand new Flight model, complete with all the necessary documents for a smooth flight (yes, even the boarding pass!)
Next destination: Seederโs Delight ๐น! After your successful takeoff from Modelville Airport, itโs time to fuel up your Flight model with some passengers and destinations. To do that, simply php artisan make:model Flight -s. This command will generate a FlightSeeder class, ready to help you stock your Flight model with tasty data seeds!
Just remember, before you can depart on your journey, youโll need to register your newly created Seeder in the database migration file. Itโs like checking-in for your flight and selecting your seat. Once registered, your Seeder will run automatically whenever you decide itโs time to take off!
And thatโs a wrap! Youโve now learned how to generate a model and a FlightSeeder class in Laravel. So grab your headphones, relax, and enjoy the flight!
Alrighty, buckle up, coding pilots! Letโs embark on an exciting journey through the vast skies of Laravel land. You know the drill โ weโre about to create a new model and controller to rule the roost. But instead of sounding like a stuffy old textbook, letโs spice things up a bit.
- First off, letโs summon our very own Flight model with a wave of our wand (okay, itโs more like typing):
php artisan make:model Flight --controller
This spellbinding command will cast the necessary files for our Flight model and its trusty sidekick, the FlightController. Itโs like having a personal aircraft manufacturing factory right at your fingertips!
- Next up, if you find yourself needing a second controller (who needs just one, am I right?), you can conjure it up with this incantation:
php artisan make:model Flight -c
This command will create a new FlightController minus the model. Itโs like having your very own wingman for those times when you need to multitask and rule multiple routes at once!
So there you have it, future Laravel luminaries โ easy peasy, right? Now that weโve conquered generating models and controllers, who knows where the winds of coding will take us next! Happy flying, and remember: โWith great power comes great responsibilityโ โ or something like that. ๐
Alrighty then! Letโs tickle those keys with a dash of humor while creating our dashing new model and companions.
Take flight and create a swanky model, FlightController resource class, and form request classesโฆ (Yeah, you heard it right!)
First off, grab your magic wand (your terminal) and letโs commence the incantation:
php artisan make:model Flight โcontroller โresource โrequests
Or, if youโre feeling extra fancy, you can say:
php artisan make:model Flight -crR
Now, watch as our little Laravel mascot whips up a model like a master chef tossing dough in the air. In this case, weโre baking up a tasty Flight model with a side of FlightController, resource class, and form request classes to top it all off!
Letโs get ready for takeoff as we set our sights on creating an application thatโll make the skies sing!
Alrighty then! Letโs embark on a thrilling adventure in Laravel-land where we code, laugh, and create fantastic models like a modern-day Leonardo da Vinci with a keyboard (and no, we wonโt paint any mona lisas!). Ready? Buckle up!
First, gather around fellow space cowboys and cowgirls because itโs time to summon our trusty sidekick - the command line interface. Type in:
php artisan make:model Flight --policy
This mysterious incantation will bring forth two magnificent creations from the depths of your Laravel project. One, a dashing model named โFlight,โ and two, a chivalrous class called โFlightPolicyโ! Itโs like creating superheroes with just a few keystrokes!
Now, our Flight model will be the fearless leader, keeping track of all your airborne adventures while our FlightPolicy class will ensure order in the skies. So, get ready to take flight and rule the digital skies together! But remember, with great power comes great responsibilityโฆ or something like that. You know, if Spiderman was a PHP artisan. ๐๐
Alrighty then! Buckle up, because weโre about to take off on an adventure thatโll make your development life a whole lot easier. Weโre talking about creating a model and all its wingmen โ migration, factory, seeder, and controller โ with just one command! Letโs get this party started:
โGentleman (or lady), start your engines!โ
php artisan make:model Flight -mfsc
Now, hereโs a quick rundown of what each letter stands for:
-
m: Model โ The blueprint of our aircraft, defining the attributes, relationships, and rules. This baby will help us navigate the vast skies of data in our application. -
f: Factories โ Like an airlineโs assembly line, but instead of manufacturing Boeings, weโre churning out dummy Flight objects to make testing a breeze! -
a: Migration โ The runway for our flight data takeoff and landing. These scripts allow us to create, modify, and manage the database schema with ease. -
s: Seeder โ A greenhouse where we can grow lush seedlings (er, seeds) of Flight records, ready for planting in our database when needed. Ideal for populating the database during deployment or testing. -
c: Controller โ The cockpit from which we steer our application. Controllers handle HTTP requests and delegate tasks to models and other services to return responses.
So, with a single command, youโve launched your very own Flight model and its entourage! Now, letโs go forth and conquer the database frontier! Bon voyage! ๐
Alrighty, buckle up, coders! Letโs embark on an adventure that would make a superhero envious. Weโre not just talking about creating a simple model here, oh no, this is a full-blown aviation extravaganza!
Take flight with one command ๐ซ๐
php artisan make:model Flight --all
Say goodbye to manual labor and hello to your very own air traffic control system in a box. With this single command, youโll generate a model, migration, factory, seeder, policy, controller, and form requests like a seasoned airline pilot.
Feeling extra fancy? No worries! Weโve got an acrobatic move for that too. ๐
When you want to touch down lightlyโฆ lide
php artisan make:model Flight -a
If youโre in a hurry or just prefer a gentle landing, this oneโs for you. It generates everything except the policy file. Just remember, no parachutes allowed! ๐
So, grab your coding helmets and prepare for takeoff! With our trusty artisan command, creating a new project is as easy as pie (or should we say, flying a kite)! ๐ฅงโ๏ธ
Alrighty, letโs dance a little Laravel jig together! ๐บ๏ธ
Spin that command line, create a pivot modelโฆ ๐
You know the drill, time to whip up a pivot model! But donโt worry, itโs not as fancy as a disco ball, just as important. Here are a couple of ways to do it:
-
The Classic Approach (for purists): php artisan make:model Member โpivot
-
Short and Sweet (for the impatient): php artisan make:model Member -p
Now, donโt be confused by the fancy names; these commands are like the trusty dancing partners you need to keep things moving smoothly on the Laravel dance floor. ๐๏ธ๐บ๏ธ
And hey, if you ever want to take a peek at your models (to make sure theyโre still got it), you can always inspect them! Just follow this link:
So there you have it! Pivot models made easy, and with a dash of humor to keep things fun. Now letโs boogie back to coding! ๐คนโโ๏ธ
Alrighty, letโs get this party started! When it comes to decoding your Laravel models like a secret agent deciphering Morse code, we got you covered. But instead of using spy gadgets, weโve got something even cooler - the model:show Artisan command!
Imagine being in an epic quest for knowledge, and this command is your trusty magical scroll revealing all a modelโs attributes and relations in one swoop (without summoning Cthulhu or any other Lovecraftian horrors). Hereโs how you summon it:
php artisan model:show Flight
P.S. If you think youโre too cool for scrolls, feel free to refer to this command as โThe Knowledge Oracle.โ Now go forth and conquer your models with style! ๐๐ซ๐งโโ๏ธ
Ahoy there, coders! ๐ซ Letโs embark on a fun journey through the skies of Laravel land, focusing on Eloquent Model Conventions. Buckle up, as weโre about to take flight! ๐
Models in our Laravel aircraft are born in the app/Models hangar, courtesy of the trusty make:model command. Letโs peek at a humble model class and dive into some Eloquentโs essential conventions:
<?php
namespace App\Models; // Yes, this is where our model lives - no need to search for the cockpit door! ๐๏ธ
use Illuminate\Database\Eloquent\Model; // We're extending the Eloquent Model, because who wouldn't want a built-in autopilot system? โ๏ธ
class Flight extends Model
{
// ...
}
Now that weโve got our wings wet with the basics, letโs dive deeper into the heart of Eloquent: table names. Guess what? Your model classโs lowercase, pluralized name is magically associated with its database table - no need for a manual takeoff coordination! ๐ฐ๏ธ For example, if your model is Flight, its database table will be named flights. Ainโt that magical? โจ
But remember, the magic only works if your models and tables share the same name pattern - no sneaky alias swaps allowed! If you have a table called aircrafts instead of airplanes, your model should be named Aircraft, not Airplane. Because even in Laravel land, consistency is key! ๐
Thatโs all for now, pilots! Keep your code clean and your models shining bright. Happy coding! ๐
Ah, the sweet symphony of code and databases! But letโs not get too carried away - weโre here to discuss something a bit more earthbound: table names.
In our example, you might have raised an eyebrow (or two) wondering where on earth Eloquent found our Flight modelโs database table. Well, buckle up! It turns out itโs like a cat - it has nine livesโฆ or rather, nine names. By convention, the modelโs table name is derived from its class name in โsnake case,โ and with a little twist of plurality. So, our Flight model dances in the skies (and databases) under the name flights. But wait, thereโs more! An AirTrafficController, well, itโs not one to be left grounded; it prefers to manage things from its air_traffic_controllers table.
But what if your modelโs table name is as elusive as a unicorn in a haystack? No problemo! You can manually assign the modelโs table name using the Table attribute, just like teaching a parrot to squawk on command:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
#[Table('my_flights')] // Here's where the magic happens!
class Flight extends Model
{
// ...
}
So there you have it! Now, go forth and conquer your databases with this newfound knowledge! Or, you know, just build some cool apps. Whatever floats your boat.
The Crown Jewels of Your Database: Primary Keys
In the grand old world of Laravel, Eloquent models are the dashing knights that gallop off to fetch data from the dark, dusty corners of your database. But these brave knights need a beacon to find their way back home โ and thatโs where primary keys come in!
By default, our dashing knights assume the corresponding table has a column named โidโ as its primary key. However, if you have a more eccentric data structure, fear not! You can specify a different column acting as your modelโs primary key using the key argument on the Table attribute:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
#[Table(key: 'flight_id')] // Now our knights will be on the lookout for Flight_ID instead of the usual ID!
class Flight extends Model
{
// ...
}
But hereโs where things get really interesting! In a conventional database, primary keys are like King Arthurโs Excalibur โ they rise and shine with incrementing integer values. However, our daring knights can also handle non-numeric or non-incrementing primary keys if you specify the keyType and incrementing arguments on the Table attribute:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
#[Table(key: 'uuid', keyType: 'string', incrementing: false)] // Our knights now have a magical compass that guides them to UUIDs instead of ordinary numbers!
class Flight extends Model
{
// ...
}
But what if you just want to give your data a chance to breathe and not have the knight automatically increment the ID? You can use the WithoutIncrementing attribute:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\WithoutIncrementing;
use Illuminate\Database\Eloquent\Model;
#[WithoutIncrementing] // Our brave knight will no longer auto-increment IDs, giving your data a well-deserved break!
class Flight extends Model
{
// ...
}
So there you have it! Now go forth and conquer your databases with the power of primary keys and Laravelโs fearless Eloquent models. Happy coding, brave adventurers! ๐ค๐ฐ
Ahoy there, coding pirates! You mightโve heard tales about composite primary keys and thought Eloquent was a one-eyed parrot with no understanding of such magic. But fear not, me hearties! This section be all about clarifying the situation for ye scallywags.
Eloquent demands that each model be adorned with at least one unique โIDโ that can help identify it like a treasure map marking buried gold. Composite primary keys, though? Well, theyโre more like a secret decoder ring or Morse code - not something Eloquent models can directly decipher (yet).
But donโt let this dampen your spirits! You can still make your databases dance by adding multi-column, unique indexes to your tables. These are the polka steps that your table will follow when Eloquent isnโt dancing with composite keys. Just remember, these additional indexes are like extra dance moves, spicing up a routine without replacing the lead role - i.e., the primary key.
Now, when it comes to unique identifiers, there be two beasts of the sea that stand out: UUIDs (Universally Unique Identifiers) andULIDs (Cleverly Named Unique Identifier). These are like compasses for your data, helping you navigate even the stormiest of relationships between tables. Eloquent can handle both of these bad boys with ease, so donโt be shy about using them to add some flair to your models!
Happy coding and may your databases always be swashbucklingly organized!
Sashay into the Sea of Sequence-less! ๐๐ฎ
If youโre tired of the mundane auto-incrementing numbers as your Eloquent modelโs primary keys, weโve got some magic for ya! Letโs take a dip in the UUID pool instead. UUIDs are like those universally unique identification cards that even Dumbledore couldnโt conjure twins for - 36 alphanumeric characters of pure, unadulterated uniqueness!
To make your model dance to this new beat, you can sprinkle a dash of the Illuminate\Database\Eloquent\Concerns\HasUuids trait on it. But remember, a good dancer always preps well - ensure that your model sports a primary key column as cool as its UUID self:
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasUuids;
// ...
}
$article = Article::create(['title' => 'Traveling to Europe']);
$article->id; // "018f2b5c-6a7f-7b12-9d6f-2f8a4e0c9c11"
By default, the HasUuids trait whips up UUIDv7 identifiers for your models, making them great for indexed database storage because they can be arranged lexicographically - just like a well-organized library!
But if youโre the type who likes to customize their dance moves, you can override the UUID creation process for specific models by defining a newUniqueId method on the model. And if you want to specify which columns should receive UUIDs, define a uniqueIds method on the model:
use Ramsey\Uuid\Uuid;
/**
* Generate a new UUID for the model.
*/
public function newUniqueId(): string
{
return (string) Uuid::uuid4();
}
/**
* Get the columns that should receive a unique identifier.
*
* @return array<int, string>
*/
public function uniqueIds(): array
{
return ['id', 'discount_code'];
}
Now, if youโre really into brevity (who isnโt?), why not try ULIDs? Similar to UUIDs, but shorter at 26 characters. Like ordered UUIDs, ULIDs can be sorted lexicographically for efficient database indexing. To step onto the ULID dance floor, you should use the Illuminate\Database\Eloquent\Concerns\HasUlids trait on your model and prepare a primary key column thatโs as unique as a snowflake:
use Illuminate\Database\Eloquent\Concerns\HasUlids;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use HasUlids;
// ...
}
$article = Article::create(['title' => 'Traveling to Asia']);
$article->id; // "01gd4d3tgrrfqeda94gdbtdk5c"
Time Travel, Laravel Style! ๐ฐ๏ธ
In our Eloquent universe, itโs as if time itself is on autopilot! By default, our models are equipped with a built-in DeLorean (created_at and updated_at columns) that automatically sets off when models are born or aged. But what if you want to defy the laws of data-time? ๐ฑ
If youโre not digging the whole time-keeping thing, no worries! You can stop the clock by setting your modelโs Table attributeโs timestamps to false. Hereโs how to do it:
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
#[Table(timestamps: false)]
class TimeTraveler extends Model
{
// ...
}
Now, if you only need to disable time travel (timestamps), thereโs a quicker way! Grab the WithoutTimestamps attribute and hop aboard:
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\WithoutTimestamps;
use Illuminate\Database\Eloquent\Model;
#[WithoutTimestamps]
class TimeTraveler extends Model
{
// ...
}
If youโre a stickler for time, and need to customize your modelโs timestamp format (weirdo), there are two ways:
- Via the
dateFormatargument on theTableattribute:
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Table;
use Illuminate\Database\Eloquent\Model;
#[Table(dateFormat: 'U')]
class TimeTraveler extends Model
{
// ...
}
- Or by using the
DateFormatattribute:
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\DateFormat;
use Illuminate\Database\Eloquent\Model;
#[DateFormat('U')]
class TimeTraveler extends Model
{
// ...
}
And if you prefer to rename the columns where timestamps are stored, just define CREATED_AT and UPDATED_AT constants on your model:
class TimeTraveler extends Model
{
/**
* The name of the "created at" column.
*
* @var string|null
*/
public const CREATED_AT = 'timeOfBirth';
/**
* The name of the "updated at" column.
*
* @var string|null
*/
public const UPDATED_AT = 'lastTimeSeen';
}
Finally, if you want to do model operations without disturbing the updated_at timestamp (time travelers beware!), you can perform them within a closure given to the withoutTimestamps method:
Model::withoutTimestamps(fn () => $post->increment('reads'));
Now go forth and bend time to your will, but remember - donโt mess with the space-time continuity! ๐๐ฐ๏ธ๐
Cosmic Navigation System (CNS) Models
By a wormhole of defaults, all our CNS models are preprogrammed to communicate with the primary dimension of data thatโs been warped for your spacecraft application. But, you know what they say: Variety is the spice of quantum entanglement! If you fancy using a different dimension for some models, the DimensionPortal attribute will be your warp drive:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\DimensionPortal;
use Illuminate\Database\Eloquent\Model;
#[DimensionPortal('The MySQL Realm')]
class SpaceVoyage extends Model
{
// ...
}
Protip: Make sure to warp your warp drives correctly, or youโll end up in a dimension filled with nothing but spaghetti code and angry cats! ๐๐
Sky-High Defaults! ๐๐ฌ
Ever found yourself staring at a freshly hatched Laravel model, wondering where its wings are? Fear not! By default, these fledglings are as empty as an air traffic controllerโs laugh-o-meter. But fear not, for with just a sprinkle of PHP magic, you can fill โem up with some swanky default attributes!
If you want your models to come pre-loaded like a luxury hotel mini-bar, you can define the default values for some of your modelโs attributes by creating an $attributes property on your model. Just remember, the values you stick in this array should be as database-ready as a well-dressed airline passenger:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* The model's runway ready defaults for attributes.
*
* @var array
*/
protected $attributes = [
'options' => '["free pillow","vegan meal"]', // Hey, we cater to all tastes!
'delayed' => false, // Just like our customers' hopes when they see their boarding time ๐ฐ๏ธ
];
}
And just like that, your models are ready for takeoff with some tasty defaults! But remember, only serve up values in their raw, storable format โ no need to add the fancy garnish yet. Thatโs what the database is for! ๐
Alright, Laravel fanatics! Letโs dive into the world of Eloquent Strictness, where your models behave just like that stubborn ex who refuses to play by the rules (unless you really want them to).
First off, we got the preventLazyLoading method, a magical spell that ensures your models load in all their glory before serving them up. It accepts an optional boolean argument - think of it as a party invitation, only Eloquent decides who gets to join. If you want to keep lazy loading out of production (because letโs face it, who needs surprises in production?), just call this method in your AppServiceProviderโs boot method:
use Illuminate\Database\Eloquent\Model;
public function boot(): void
{
Model::preventLazyLoading(! $this->app->isProduction()); // Don't invite lazy loading to the production party!
}
Next up, we have the preventSilentlyDiscardingAttributes method. Picture this: youโre trying to set an attribute on your model during local development, but itโs like that pesky ex who just doesnโt listen. To make sure Eloquent throws a tantrum (in the form of an exception) instead of silently ignoring your requests when you try to set an unfillable attribute, give this method a shout:
Model::preventSilentlyDiscardingAttributes(! $this->app->isProduction()); // Tell Eloquent not to be shy about throwing exceptions during local development!
Now that your models are ready to play by the rules (most of the time), itโs time to unleash them on the world. Happy coding, Laravelistas!
Flying High with Models
Alright, buckle up and fasten your seatbelts! After crafting a model and its swanky database table (check out our sweet migration guide for more deets), itโs time to dive into the world of data retrieval. Think of each Eloquent model as your personal aviator, guiding you through the vast skies of databases!
The all method on these models serves as our runway to take off and grab all records from their associated database table:
use App\Models\Flight;
// Prepare for liftoff
$flights = Flight::all();
// Announce the names of each flight (just like an airport PA system)
foreach ($flights as $flight) {
echo $flight->name;
}
Now, if youโre feeling a bit more adventurous and want to customize your queries (think of it as flying with autopilot off), head over to our query builder guide for some fancy maneuvers!
Alrighty, buckle up and letโs dive into the realm of Eloquent! Think of it as your trusty sidekick at a high-stakes casino, but instead of cards or dice, weโre dealing with data.
Our hero, the all method, pulls out all the stops and fetches every record from the modelโs table. But wait, this isnโt just any common-or-garden sidekickโEloquent models are actually undercover query builders! Thatโs right, they can morph into a versatile, flexible toolbox of database queries whenever they need to step up their game.
So, hereโs where the fun begins:
$flights = Flight::where('active', 1)
->orderBy('name')
->limit(10)
->get();
This snippet of code is our Eloquent model, undercover as a flight booking system, sneakily adding some extra conditions to its query. Itโs like a seasoned detective filtering through the crime database for only โactiveโ suspects and sorting them alphabetically by nameโall before serving you up the top 10 results!
Now, just because Eloquent is a secret agent of queries doesnโt mean it doesnโt have friends in high places. Be sure to check out Laravelโs query builder documentation for a rundown of the various tricks up its sleeve. You can use these techniques whenever you feel like unleashing the full potential of Eloquent and making your queries dance to your tune!
Hereโs to making data retrieval as entertaining as an action-packed movie! ๐ฟ๐ฌ
Ahoy there, coders! Sail with me into the realm of Laravel models, where data soars through the skies like a majestic flock of phpbirds.
First off, letโs talk about refreshing your models - much like a jet engine getting a much-needed oil change mid-flight! Say youโve got yourself an Eloquent model (weโll call him Captain Data) thatโs been retrieved from the database (letโs say heโs just landed in Paris).
Now, if you want to give this fella a quick touch-up before takeoff for the next destination (say, London), you can use the fresh method. Itโll fetch Captain Data anew from the databases without affecting his current state:
$flight = Flight::where('number', 'FR 900')->first(); // Captain Data lands in Paris
$refreshedFlight = $flight->fresh(); // Gives him a new boarding pass for London
But wait, thereโs more! If you want to give your model a full-on makeover with the latest data from the database (letโs say Captain Data had an unscheduled layover), then you need the refresh method. Not only will it update Captain Data himself, but all his loaded relationships too:
$flight = Flight::where('number', 'FR 900')->first(); // Captain Data lands in Paris
$flight->number = 'FR 456'; // He decides to join a different flight!
$flight->refresh(); // Gives him a new boarding pass for the updated flight and updates all his relationships
$flight->number; // "FR 900" (he couldn't resist coming back to us, can you blame him?)
So there you have it! Keep your Laravel models fresh as a daisy (or a phpbird) with these handy methods. Happy coding, and remember: never trust a model that doesnโt get a fresh check-up every now and then!
Alrighty, letโs dive into the magical realm of Laravel Collections! You might think Eloquent is just a fancy barista pulling espressos from your database, but little do you know, itโs actually spinning plates too. When Eloquent serves up multiple records with methods like all and get, what lands on your table isnโt just any ordinary PHP array - nope, itโs a sparkling, shimmering instance of Illuminate\Database\Eloquent\Collection!
Now, this isnโt some circus act; itโs Eloquentโs way of saying โhey, I got more tricks up my sleeve!โ The Collection class, in all its glory, extends Laravelโs base Illuminate\Support\Collection class, offering a smorgasbord of deliciously handy methods for massaging your data like a pro.
Take the reject method, for instance. Itโs like your very own data dietitian, helping you trim the fat from collections based on the results of an invoked closure:
$flights = Flight::where('destination', 'Paris')->get();
$flights = $flights->reject(function (Flight $flight) {
return $flight->cancelled;
});
But wait, thereโs more! The Eloquent collection class doesnโt just stop at Laravelโs base collection methods. Oh no, it goes the extra mile and provides a few extra-crunchy methods specifically tailored for juggling collections of Eloquent models.
And hereโs the cherry on top: since all Laravel collections are certified PHP iterables, you can loop over them like theyโre your favorite Sunday brunch buffet:
foreach ($flights as $flight) {
echo $flight->name;
}
Now thatโs what I call a data feast! So next time youโre handling multiple records, remember - it ainโt just an array, itโs a Collection with a capital โCโ and a whole lot of flair. Bon appรฉtit, data wranglers! ๐ฅณ๐ฝ๏ธ๐
Eloquentโs Magical Memory Box ๐ฉ๐ฌ
Letโs face it, no one wants to deal with a brain cramp after loading tens of thousands of airplane tickets (Eloquent records)! The all or get methods are like trying to squeeze a herd of flying unicorns into a broom closet - disaster is inevitable! ๐ฆ๐ช
Fear not, for the mighty chunk method is here to save the day! This magical wand will whisk away a manageable portion of those sky-high models, leaving them in a cozy, memory-friendly pile for you to process.
To use this sorcery, simply point your wand at a model (in this case, our dear Flight) and utter:
use App\Models\Flight;
use Illuminate\Database\Eloquent\Collection;
Flight::chunk(200, function (Collection $flights) {
foreach ($flights as $flight) {
// ... Perform some mystical incantations on the flights...
}
});
The first number youโll conjure up is the size of each chunk, while the closure (the secret spell) will be cast for every batch retrieved from the database. Each batch of records will be delivered to the closure, one by one, like treats on a Halloween trick-or-treat trail!
Now, if youโre updating those airplane tickets and filtering them based on some column, itโs time to dust off your cloak and use the chunkById method. The regular chunk can be as unpredictable as a mischievous poltergeist in this situation, leading to results more frightening than a haunted house!
Flight::where('departed', true)
->chunkById(200, function (Collection $flights) {
$flights->each->update(['departed' => false]);
}, column: 'id');
The chunkById and lazyById methods cast their own enchantments, adding โwhereโ conditions to the query. This means you should group your own conditions within a spell (closure) for optimal results:
Flight::where(function ($query) {
$query->where('delayed', true)->orWhere('cancelled', true);
})->chunkById(200, function (Collection $flights) {
$flights->each->update([
'departed' => false,
'cancelled' => true
]);
}, column: 'id');
Chunking with Lazily Loaded Collections (aka The Magical Bag Oโ Models)
Ah, the Laravel way! If youโve ever needed to sift through a mountain of flight data like a modern-day Goldilocks, youโll love our Lazy Collections. Picture it like this: instead of lugging around giant, unwieldy chunks of data (weโre looking at you, chunk method), we give you a nifty bag oโ models, each magically appearing one by one as you rummage through!
use App\Models\Flight;
foreach (Flight::lazy() as $flight) {
// One flight at a time, just the way Goldilocks prefers it.
}
But hereโs where things get really interesting - if youโre updating a column on your flights while youโre already digging through them, you wouldnโt want to accidentally skip any, right? No worries, weโve got you covered with the lazyById method. This clever chap grabs only the models whose id is strictly greater than the last model from the previous chunk.
Flight::where('departed', true)
->lazyById(200, column: 'id') // Start from flight 201 onwards.
->each->update(['departed' => false]);
And if you fancy some reverse sorting (who doesnโt?), you can always use the lazyByIdDesc method to filter your results based on the descending order of the id.
Now, arenโt you glad you have Laravel in your corner, helping you navigate those mountains of data like a boss?
Alrighty then! Letโs dive into the magical world of Laravel cursors, a memory-saving superhero that swoops in to save your application from crashing under the weight of tens of thousands of Eloquent model records.
Just like our friendly neighborhood Spiderman, the cursor method slings its web to only catch one model at a time, significantly reducing the amount of memory used during iterations. But donโt worry, itโs not shy about jumping in for more when needed!
Attention
Remember, this superhero only carries one model at a time, so it canโt load up on relationships like your friendly neighborhood Avengers. If you need some relationship action, consider calling in the lazy method instead.
Behind the scenes, the cursor method uses PHP generators (think of them as magical incantations that summon models on demand), so you can rest easy knowing thereโs no need for a crystal ball to see the future:
use App\Models\Flight;
foreach (Flight::where('destination', 'Zurich')->cursor() as $flight) {
// ...
}
The cursor method returns an Illuminate\Support\LazyCollection instance, giving you the power to use many of your favorite collection methods while keeping memory consumption in check:
use App\Models\User;
$users = User::cursor()->filter(function (User $user) {
return $user->id > 500;
});
foreach ($users as $user) {
echo $user->id;
}
Although the cursor method is a memory saver extraordinaire, it can still run out of breath if faced with too many models at once (thanks to PHPโs PDO driver caching all raw query results in its buffer). If you find yourself dealing with an overwhelming number of Eloquent records, itโs time to call in the lazy method for backup.
Now that weโve covered the basics, itโs time to explore the world of advanced subqueries! (Just wait till you see this guy in action!) Stay tuned for more fun and educational adventures with Laravel! ๐๐
Ahoy there, query pirates! Youโve ventured beyond the shallow end of SQL and now find yourself navigating the deep waters of subqueries. Fear not, for weโll guide you through these treacherous seas with a hearty laugh and a dash of sass.
Subquery Selects
Subquery selects allow you to nest one SQL query within another like Russian dolls in a game of Balalaika Tetris. The outer query can reference the inner query, and itโs all done with such finesse that even Captain Kirk would be impressed.
Hereโs an example of a subquery in Laravel:
$users = DB::table('users')
->whereIn('id', function ($query) {
$query->select('user_id')
->from('friendships')
->whereColumn('user_id', '=', 'users.id');
})
->get();
This little number is saying: โGimme all the users whose IDs are friends with at least one other user.โ Sounds like a party, doesnโt it? ๐๐ฅณ
Subquery Joins
Now, buckle up, because weโre about to enter the realm of subquery joins. These are like when you find a genie in a bottle and it grants you three wishes - but instead of genies, itโs just SQL queries helping each other out.
$posts = DB::table('posts')
->where(function ($query) {
$query->where('user_id', 1)
->orWhereIn('user_id', function ($innerQuery) {
$innerQuery->select('user_id')
->from('friendships')
->whereColumn('friend_id', '=', DB::raw('users.id'));
});
})
->get();
This one is saying: โGive me all the posts either written by user 1 or written by any of user 1โs friends.โ Sounds like a pretty good deal, if I do say so myself! ๐ค๐ธ
And there you have it, chums! Armed with these subquery skills, you can sail the seas of SQL with confidence and charm. Remember to have fun along the way, because thatโs what makes the journey worthwhile! ๐๐
Alright, buckle up, because weโre about to embark on a thrilling query adventure in Laravel!
Subqueries: The Secret Sauce for Table Bonding ๐
Eloquent isnโt just another boring date at the disco, oh no, it comes packing some advanced subquery swag that lets it mingle with related tables like a boss! Picture this: weโve got a table of flight destinations and a table of flights bound for those destinations. The flights table keeps a record of the arrived_at timestamp, marking when each flight touched down at its destination.
Now, with the subquery powers bestowed upon the query builderโs select and addSelect methods, we can scoop up all the destinations and the name of the last flight to arrive at each one in a single swoop:
use App\Models\Destination;
use App\Models\Flight;
Here's where the magic happens! We're using Destination as our wingman, helping us fetch data from Flight while keeping things casual with a few lines of code.
return Destination::addSelect([
'last_flight' => Flight::select('name')
->whereColumn('destination_id', '=', 'destinations.id') // Just like two peas in a pod!
->orderByDesc('arrived_at') // Sorting them out, who else but Laravel can do this?
->limit(1) // And just like that, we've got our winner!
])->get();
And there you have it, folks! A single query that grabs all the destinations and their last arriving flights. Thatโs what I call a smooth dance floor move! ๐๐บ๏ธ
Alright, buckle up, aviators! Letโs dive into the world of Laravelโs query builder where weโre about to perform a subquery order like itโs the final approach to landing on a busy runway.
Imagine youโve got a flight schedule with a bunch of destinations and flights, and you want to find out which destination was the last one to have a flight land. Sounds like a mission for your trusty query builder!
Hereโs where the magic happens:
return Destination::orderByDesc(
Flight::select('arrived_at') // Grab the landing times, y'all!
->whereColumn('destination_id', 'destinations.id') // Match the destinations, like a perfect pair of gloves
->orderByDesc('arrived_at') // Sort by time, with the latest landing first
->limit(1) // One landing time per destination, thanks!
);
And voila! With this single database query, youโve got yourself a destination that just saw its last flight touch down. Now go forth and conquer those runways, you database-mastering ninja! ๐๐ฅ๐ฌ
Soaring Solo with Laravelโs Model BFFs!
Ever felt like you just want to cuddle up with one model instead of a whole bunch? Well, my friend, thatโs where our dashing duo - find, first, and the slightly mysterious firstWhere come into play!
Unlike their collection counterparts, these gents donโt bring along a whole gang of models to the party. Instead, they graciously return a single model instance:
use App\Models\Flight;
// Let's find ourselves a flight by its primary key...
$flight = Flight::find(1);
// Here we're seeking out the first flight that's active and ready to fly...
$flight = Flight::where('active', 1)->first();
// If 'firstWhere' is more your style, go ahead and give it a whirl!
$flight = Flight::firstWhere('active', 1);
But what if you find yourself in a hangar with no planes? These chivalrous charmers know just how to handle that: the findOr and firstOr methods will return a single model or, if none are found, theyโll politely execute the given closure. The returned value from the closure then becomes your new best friend:
$flight = Flight::findOr(1, function () {
// ...oh look, it's our backup plane!
});
$flight = Flight::where('legs', '>', 3)->firstOr(function () {
// ...it looks like we have to send out an SOS for a new plane...
});
Oh, and letโs not forget about those pesky not-found exceptions. In case you ever stumble upon empty hangars, these methods will kindly toss you a life jacket in the form of a closure:
Flight::findOrFail(1); // This guy throws an exception if no flight is found.
Alrighty, letโs dive into the exciting world of Laravel exceptions! Now, if you ever find yourself in a pickle where your model is nowhere to be found (like a misplaced pair of socks), you can chuck an exception its way. This comes in super handy when youโre working on routes or controllers. The findOrFail and firstOrFail methods are your new best friends here - theyโll scour the database, retrieve the first result of the query, but if Mr. Model is nowhere to be found, theyโll hurl an Illuminate\Database\Eloquent\ModelNotFoundException.
$flight = Flight::findOrFail(1); // Hey! We found your flight, Captain! But what if we didn't? Well, we'd throw a party... for the exception!
$flight = Flight::where('legs', '>', 3)->firstOrFail(); // If no flight with more than three legs is found, it's time to call the avian psychologist!
Now, if you let this ModelNotFoundException run wild without catching it, itโll auto-pilot a 404 HTTP response right back to your client. Talk about a high-speed chase!
use App\Models\Flight;
Route::get('/api/flights/{id}', function (string $id) {
return Flight::findOrFail($id); // If this doesn't find the flight, it's time to start playing missing person games with the flight data!
});
Happy coding, and remember - when in doubt, throw an exception! ๐๐ฅ
Ahoy there, Laravel pirate! Sail with me through the stormy seas of database operations, where the firstOrCreate and firstOrNew methods are our trusty compass and map.
First off, letโs talk about firstOrCreate. Picture this: ye be searching for a specific record in yer database, but itโs gone walkies. Fear not! With firstOrCreate, ye can either find the blighter or create a brand new one if itโs vanished without a trace. How does it work, ye ask? Simple as a shipwrecked sailorโs wish for rum: it merges the first array argument with an optional second array to conjure up a spankinโ new record if the original ainโt found!
Now, firstOrNew is more like a friendly sea creature thatโll either lure ye towards the existing record or entice you to craft a new one. Just like firstOrCreate, it embarks on a quest for your desired record, but if it comes back empty-handed, itโll bestow upon ye a freshly minted model instance. Be aware though: this ship hasnโt been anchored in the database yet! If ye want to keep it from drifting away, yeโll need to call its save method and set sail for permanent waters.
Here be examples, matey:
use App\Models\Flight;
// Sail towards a flight by name or create one if it don't exist yet...
$flight = Flight::firstOrCreate([
'name' => 'London to Paris'
]);
// If ye be after a specific flight, and it's not around, ye can create one with extra attributes...
$flight = Flight::firstOrCreate(
['name' => 'London to Paris'],
['delayed' => 1, 'arrival_time' => '11:30']
);
// If ye be unable to locate a flight by name, ye'll get a new Flight instance instead...
$flight = Flight::firstOrNew([
'name' => 'London to Paris'
]);
// If ye be on the lookout for a flight from Tokyo to Sydney, and it ain't been found yet, ye'll receive a fresh Flight instance with extra attributes...
$flight = Flight::firstOrNew(
['name' => 'Tokyo to Sydney'],
['delayed' => 1, 'arrival_time' => '11:30']
);
Counting, Summing, and Maximizing Your Queries!
In the thrilling world of Eloquent models, we donโt just serve up fancy airline seats; we also whip up some mean data aggregates! So buckle up as we take a fun-filled journey through the count, sum, max, and other aggregate methods offered by Laravelโs query builder (cue drumroll).
Ready for some numerical shenanigans? Here we go:
$count = Flight::where('active', 1)->count(); // How many flights are currently in the sky with active status?
$max = Flight::where('active', 1)->max('price'); // What's the priciest flight that's actually flying right now?
But hey, who needs models when you can get a simple scalar value, am I right? Just remember, these methods donโt serve you an Eloquent model instance like a fancy dinner at a five-star restaurant. Instead, they dish up some good olโ fashioned numbers!
Ahoy there, code-wrangling swashbucklers! Youโve come to the right place if youโre ready to dive into the high seas of Laravel model manipulation. Buckle up as we sail through the fascinating world of inserting and updating models. Aye, aye, captain!
Inserting Models: The Pirateโs Treasure
Adding new models is like discovering hidden treasure, and Laravel makes it as easy as navigating a pirate ship through a storm! Use the trusty fill() method to pack your model with data. Hereโs an example:
$newUser = new App\Models\User;
$newUser->fill([
'name' => 'Captain Swashbuckler',
'email' => 'swashbuckler@pirate.com',
]);
// Save the treasure, matey!
$newUser->save();
And just like that, youโve added a new user to your database. Just remember to watch out for the Kraken โ that save() method can be a bit of a rogue wave at times!
Updating Models: The Polly Parrotโs Squawk
Updating models is like teaching Polly the parrot to say something new. You want her to squawk out the latest updates, right? To update a model in Laravel, you can use the update() method and pass an associative array containing the data you want to change. Watch this:
$user = App\Models\User::find(1); // Find our parrot (user) by id
$user->name = 'Captain Jack Sparrow'; // Change what we want Polly to squawk out loud
// Train Polly to say her new name
$user->save();
And once again, the pirate ship sets sail with a new name! Just remember to keep your code clean and dry โ no need for a barrel of rum here!
Now that youโve learned the ropes on inserting and updating models, itโs time to set sail on your own quest. Happy coding, brave souls! May all your SQL queries be successful and your controllers never leak! ๐ดโโ ๏ธ๐๐
Ahoy there! Letโs dive into the world of data manipulation in Laravel, where weโre not just fishing for models, but also casting our line to add new catches to the database! Eloquent, being our trusty fishing rod, simplifies the process like a pro angler.
To drop a new record into the ocean of data, you first need to create a new model instance and bestow it with attributes. Think of it as naming your fish before throwing it into the pond!
<?php
namespace App\Http\Controllers;
use App\Models\FishTank; // Let's rename Flight to FishTank for a bit of fun!
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class FishTankController extends Controller
{
/**
* Add a new fish to the tank.
*/
public function splash(Request $request): RedirectResponse
{
// Ensure the request is squeaky clean...
$fish = new FishTank; // Instantiate a new model instance
$fish->name = $request->name; // Give it a name from the incoming HTTP request
$fish->save(); // Cast it into the database!
return redirect('/tank');
}
}
In this whimsical example, weโve bestowed our new model with a name attribute from the incoming HTTP request. Once save() is called, our little fishy friend finds its new home in the database. The model automatically gets tagged with a created_at and updated_at timestamp when itโs saved, so no need to worry about setting them manually.
Now, if youโd like to add your fishy friend within a secure aquarium transaction, use the saveOrFail() method:
$fish->saveOrFail(); // If anything goes awry during the save, our transaction will perform an aquatic CPR!
Alternatively, you can employ the create() method for a one-liner magic trick. The newly created model instance will be handed back to you:
use App\Models\FishTank;
$fish = FishTank::create([
'name' => 'Goldfish Gordon', // A new goldfish with style!
]);
Before using the create() method, donโt forget to specify either a Fillable or Guarded attribute on your model class. This precaution is taken because by default, Eloquent models are well-protected against unwanted mass assignments (like an octopus sneaking extra arms into the tank!). For more info on mass assignment, please consult our mass assignment documentation.
Now go forth and conquer the database with your newfound knowledge and a touch of humor! Keep those fish tanks populated and happy fishing!
Updatinโ Thangs!
Alright, buckle up for a ride through the wild world of model updates! The save() method is like the cherry on top of your database sundae - perfect for sprucinโ up models already chillinโ in your database. To get things started, track down your model with Flight::find(1), then give it a fancy new name like โParis to Londonโ, and voila! Call the save() method, and our system takes care of updating the updated_at timestamp for ya - no need to beg or plead, just sit back and relax:
use App\Models\Flight;
$flight = Flight::find(1);
$flight->name = 'Paris to London';
$flight->save();
Feelinโ adventurous? Wrap your model updates in a transaction with the updateOrFail() method. If something goes awry during the update, our system will roll back the transaction faster than you can say โoops!โ
$flight->updateOrFail(['name' => 'Paris to London']);
Sometimes, you might need to update an existing model or create a new one if none exists. The firstOrCreate() method is the perfect wingman for that situation - it handles the save for ya!
Hereโs an example of where our flight might need a price drop if it already exists or a new destination if it doesnโt:
$flight = Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99, 'discounted' => 1]
);
When youโre updating models with methods like firstOrCreate() or updateOrCreate(), it can be tricky to know whether a new model was born or an existing one got a makeover. The wasRecentlyCreated property helps out here - it lets ya know if your model made its debut during this lifecycle:
$flight = Flight::updateOrCreate(
// ...
);
if ($flight->wasRecentlyCreated) {
// A new flight record was just inserted...
}
And thatโs a wrap! Now you know how to make your models shine brighter than a disco ball at a 70โs party. Happy updating!
Alright, buckle up, folks! Letโs dive into the world of bulk updates in Laravel โ where you can update multiple flights without breaking a sweat (or your keyboard). Imagine youโre a flight controller trying to give San Diego a little extra love by delaying all active flights bound for that sunny paradise.
// Just like a well-planned travel itinerary, we've got our destinations mapped out!
Flight::where('active', 'yes, captain!')
->where('destination', 'San Diego')
// Tada! Flights delayed, just in time for the sunset
->update(['delayed' => 1]);
Now, this magical update method requires an array of column and value pairs โ perfect for a quick makeover on your flights. Once youโve given your models a new look, itโll return the number of affected rows โ just so you know how many passengers are now stuck with you!
Attention
Proceed with caution when deploying mass updates via Eloquent. Why? Well, these flights never actually show up in your models during the update process! No need to worry about saving or updated events for this bunch โ theyโre flying straight into the database without stopping for refreshments (or event listeners).
Hope you enjoyed this little journey through Laravel land! Happy coding! ๐๐ฌ
Ahoy there, shipmates! Buckle up as we dive into the nitty-gritty of Eloquent attribute shenanigans! These methods are like the Captainโs log for your models, helping you keep tabs on their internal state and the antics of their attributes.
First off, we have the isDirty method. This sea shanty tells you if any of the modelโs attributes have been tampered with since they were first boarded aboard the good ship Eloquent. You can even inquire about specific attributes or a list of them to see whoโs been messing around with what.
Next, thereโs the isClean method. It serves as the barman, telling you which attributes have stayed put since they joined the crew. Like isDirty, you can query for specific attributes if youโre curious about a certain rascally pirate.
Now, for the fun part โ the wasChanged method! This parrot on your shoulder will let you know if any attributes were altered when the model last took a plunge into the database waters. Again, feel free to inquire about specific attributes or groups of them.
The getOriginal method is like finding the original shipโs log โ it spills the beans on the attributes as they were first discovered. You can also ask for specific attributes if youโre interested in a certain crewmemberโs backstory.
Last but not least, we have getChanges and getPrevious. These methods serve as your navigational charts, showing you which attributes changed during the last voyage and what they were before the ship set sail.
Now that youโve got the hang of these swashbuckling methods, you can sail the high seas of data manipulation with confidence! Arrrr matey! ๐ค๐ดโโ ๏ธ
Alrighty, grab your coder hat and letโs dive into the thrilling world of Laravel mass assignment! ๐
First off, imagine youโre a superhero saving the day with a single PHP statement. The create method is your trusty sidekick, helping you create a brand-new model hero just like that! ๐ฆธโโ๏ธ
use App\Models\SuperHero;
$superman = SuperHero::create([
'name' => 'Clark Kent',
]);
But, before our sidekick can start saving the world, it needs a badge to prove its trustworthiness. In our case, that badge is either a Fillable or Guarded attribute on your model class. These attributes are required because by default, all Eloquent models come with a secret superpower - protection against mass assignment vulnerabilities!
A mass assignment vulnerability occurs when a shady villain passes an unexpected request field and changes a column in your database that you didnโt expect. For example, a mischievous user might send a lives_under_rock parameter, which could allow the user to change their address without being noticed! ๐
To make our superhero trustworthy, we should define which attributes we want to be mass assignable. We can do this using the Fillable attribute on the model. For example, letโs make the name attribute of our SuperHero model mass assignable:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
#[Fillable(['name'])]
class SuperHero extends Model
{
// ...
}
Once weโve defined which attributes are mass assignable, our superhero can start saving the world with the create method. The create method returns the newly created superhero instance:
$superman = SuperHero::create(['name' => 'Clark Kent']);
But what if you already have a superhero instance and want to give it a new identity? Simply use the fill method to update its attributes:
$superman->fill(['name' => 'Super Clark']);
Now that our superhero is all set, itโs time to save the day! ๐ช๐ฆธโโ๏ธ
Ah, the world of Laravel! Where data meets humor and everything is a little bit magical. Letโs talk about JSON columns, shall we?
Mass Assignment and JSON Columns: The Magic of Data Manipulation (with a dash of comedy)
When dealing with JSON columns, itโs not just about shoving data into them haphazardly. No, no! Each column needs to be invited to the party, so to speak, by being listed in your modelโs Fillable attribute. Why? Because Laravel is a responsible host who checks IDs at the door for security reasons.
use Illuminate\Database\Eloquent\Attributes\Fillable;
// We're throwing a JSON party! Who's invited? Only options->enabled.
#[Fillable(['options->enabled'])]
class Flight extends Model
{
// ...
}
And here comes the twist: Laravel is also a stickler for rules, so when youโre using the Guarded attribute, it wonโt let you update nested JSON attributes. Itโs like having a bouncer who only lets in the main guests but keeps the sub-guests waiting outside.
So, there you have it! A little bit of Laravel magic, a dash of humor, and a lesson in data security. Keep on coding, my friends! ๐๐๐
Unleashing the Power of Mass Assignability! (But remember, with great power comes great responsibility!)
If youโre feeling a tad lazy and want your model attributes to be as obedient as a well-trained puppy, you can use the Unguarded attribute on your model. But beware, unguarding your model is like giving your pet the keys to the fridge - it might end up with more treats than it bargained for!
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Unguarded as UnleashThePowerOfMassAssignability;
use Illuminate\Database\Eloquent\Model;
#[UnleashThePowerOfMassAssignability]
class Flight extends Model
{
// ...
}
Now, remember when you use Unguarded, itโs like giving your pet the freedom to roam around without a leash. You should always double-check and hand-craft the arrays passed to Eloquentโs fill, create, and update methods, ensuring they only contain the treats (er, attributes) you want your model to consume:
// Hand-crafted array of treats (attributes) for your model
$flightTreats = [
'departure' => 'Dubai',
'arrival' => 'London',
'airline' => 'Emirates',
// Only include the attributes you want to set here!
];
// Feed your model with these treats (attributes)
$flight = Flight::create($flightTreats);
And that, my friend, is how you unleash the power of mass assignability in a responsible manner! (Well, as responsible as one can be when dealing with pets and Laravel.)
Ahoy there, intrepid Laravel developers! Letโs dive into the thrilling world of Mass Assignment Exceptions - where secrets are whispered to models under the cover of darkness and forgotten forever!
By nature, attributes that arenโt filled with the Fillable attribute charm are silently shushed away during mass-assignment operations. In production, this is as quiet as a mouse in a library, but during local development, itโs like watching paint dry โ exciting, right? So, you might wonder why your model changes refuse to cooperate when youโre just trying to flex your creative muscles.
But fear not! Laravel offers the solution with an explosive dose of excitement: the preventSilentlyDiscardingAttributes method! This is like sprinkling rocket fuel on a boring development cycle. Hereโs how you can trigger it:
use Illuminate\Database\Eloquent\Model;
/**
* A rousing call to arms for any application services.
*/
public function boot(): void
{
Model::preventSilentlyDiscardingAttributes($this->app->isLocal());
}
In this code, weโre essentially saying: โListen up, models! If weโre in development mode, donโt sneak away my unfillable attributes without a fight!โ So go ahead and add some pizazz to your development process by keeping things loud and clear โ just like a roller coaster ride at an amusement park! ๐ข๐๐ฅ
Alrighty then! Buckle up, because weโre about to dive into the thrilling world of database operations with a twist of humor, all thanks to Laravelโs upsert method!
This nifty little function is like a Swiss Army knife for your records. It can either update or create them in one atomic, indivisible operation - just like Batmanโs wrist gadgets but with less capes and more databases. The first argument is where you stash the new values, while the second one lists the columns that make each record unique within its table. Lastly, the third argument is an array of columns that will be updated in case a matching record already exists in the database - itโs like having a magic wand for your data!
Airplane::upsert(
[
['takeoff_city' => 'Oakland', 'final_destination' => 'San Diego', 'fares' => 99],
['takeoff_city' => 'Chicago', 'final_destination' => 'New York', 'fares' => 150]
],
uniqueBy: ['takeoff_city', 'final_destination'], update: ['fares']
);
Caution
Donโt forget to add a โprimaryโ or โuniqueโ index on the columns listed in the second argument of
upsert. If you donโt, our friendly neighborhood Spider-dev (SQL developer) wonโt be able to help find existing records. Also, if youโre using MariaDB or MySQL, they might not listen to your specific instructions and use their own indexes instead โ a classic case of stubbornness in action!
Ahoy there, matey! Letโs talk about deleting models in Laravel, shall we? Itโs not as grim as it sounds, promise!
To vanquish a model with a single bound, you can summon the mighty delete method upon your model instance:
use App\Models\Aircraft; // You know, like the Titanic, but hopefully without the iceberg.
$aircraft = Aircraft::find(1); // We've found our culprit!
$aircraft->delete(); // And sent it to the depths of Eloquent's database.
But what if you fancy yourself as a daredevil and want to delete the model within a transaction? Fear not, my friend! You can utilize the deleteOrFail method. If anything goes awry during the delete, itโll be like the Titanic all over again, but with your transaction automatically rolling back instead of sinking!
$aircraft->deleteOrFail(); // One misstep and down go we go!
Now you know that deleting models in Laravel can be as fun as a sea shanty and nearly as dangerous as navigating the treacherous waters of Bermuda Triangleโor perhaps not, but at least you have all your data safe and sound! ๐ค๐ผ
Ahoy there, Laravel pirates! Letโs set sail through the seas of deletion, shall we?
Vanquishing an Existing Model with Its Magic Key (AKA Primary Key)
In the pirate tale above, we were initially searching high and low for our fabled model before giving it the old heave-ho. But, ye scurvy dogs, if youโve got the magic key of your model, you can delete it like a true buccaneer without even saying โAvast!โ to โretrieveโ it first. Just holler at the destroy method and watch โem walk the plank:
The ship 'Flight' is now doomed! Calling destroy on its primary key 1... *splash*
The ships 'Flight', 'Flight', and 'Flight' are all sinking! destroy() takes multiple keys, like so: Flight::destroy(1, 2, 3)
Or if you're feeling fancy, gather ye primary keys in an array and call destroy on that! Flight::destroy([1, 2, 3])
And for the extra-fancy, turn your primary keys into a collection (we'll teach ya later!) and call destroy on that, too: Flight::destroy(collect([1, 2, 3]))
Yarrrr
The
destroymethod might be a one-legged parrot at heart, but it takes its job seriously. It loads each model individually and calls the โdeleteโ method on them, so that thedeletinganddeletedevents are properly dispatched for each shipmate.
Now, if your models have been given a second chance at life through soft deletions, you can unleash the kraken on โem with the forceDestroy method:
The ship 'Flight' is about to meet its end! Calling forceDestroy on its primary key 1... *splash* (this time, for good)
Alrighty then! Letโs dive into the world of Eloquent query deletions, shall we? Imagine youโre a pilot trying to scrub those pesky inactive flights off your roster. No worries, our trusty Eloquent queries are here to help!
// Marking all inactive flights for takeoff out of service ๐๐ฌ
$inactiveFlightClearance = Flight::where('active', 0)->delete();
// Don't forget to check if the clearance was granted ๐
if ($inactiveFlightClearance) {
echo "Inactive flights cleared for deletion!";
} else {
echo "Looks like those inactive birds are sticking around. Better luck next time, captain.";
}
Now, if youโre feeling really bold and want to wipe out the entire flight table, well buckle up for this wild ride!
// Time for a complete airport shutdown (just kidding... sort of) โ๏ธ๐ซ
$airportLockdown = Flight::query()->delete();
// Make sure passengers are informed about the lockdown ๐ฃ
if ($airportLockdown) {
echo "All flights have been grounded. Please find alternative transportation.";
} else {
echo "Flight schedules remain unchanged for now, folks!";
}
[โ๏ธ WARNING โ๏ธ] When you pull off a mass delete via Eloquent, remember that the
deletinganddeletedmodel events wonโt be dispatched for the evicted models. Itโs because they werenโt even invited to the party when we threw them out!
[โ๏ธ Bon Voyage โ๏ธ] Now that you know how to delete those pesky models, grab your luggage and head on over to the next section of this fabulous documentation journey!
Soft-Deletey McSoftFace (or, How I Learned to Stop Worrying and Love the Trash Can)
Oh, where have you been? Hiding in the dark recesses of your database, playing hide-and-seek with your precious records? Well, fear not! For Eloquent has come to your aid once again, this time in the form of a charming trait named SoftDeletes.
Think of it as the invisible cloak of the database world โ it makes your models disappear, but only temporarily. Instead of obliterating them from existence like some rogue Galactic Empire, it sets a deleted_at attribute on them, marking their disappearance date and time. To bestow this magical trait upon a model, simply add Illuminate\Database\Eloquent\SoftDeletes to your trait list:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Flight extends Model
{
use SoftDeletes;
}
Now, letโs add a deleted_at column to your database table. Laravelโs trusty schema builder comes equipped with the perfect tool for this:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
Schema::table('flights', function (Blueprint $table) {
$table->softDeletes();
});
And if you ever want to undo the soft deletion, simply call $table->dropSoftDeletes().
When you summon the mighty delete method on a model, itโll set the deleted_at column accordingly. But donโt worry โ the record will still be sitting pretty in the table, ready for its grand comeback. When querying soft-deleted models, theyโll vanish like Houdini from your results, leaving only the living and the proudly undeleted behind.
To check if a model has been sent on a one-way trip to Siberia (er, deleted), you can employ the trashed method:
if ($flight->trashed()) {
// Oh noes! This flight's gone missing!
}
So there you have it โ a lighthearted guide to soft deleting in Laravel. Now, go forth and save your records from the cold embrace of eternity! Just remember: every deleted model is only as dead as the next migrationโฆ or something like that.
Alright, letโs get this party started! You know the drill โ a model got deleted and now youโre thinking, โWhoa, too soon!โ Well, have no fear, Laravel is here to help you resurrect that model from the dead. Letโs call it โun-zombifyingโ instead of restoring, shall we?
Un-Zombifying Soft Deleted Models
So, your model went on a one-way trip to Modelville Cemetery, and now you want to bring it back to life. No problemo! To un-zombify a soft deleted model, simply summon the restore method like a Jedi calling upon the Force:
$flight->unZombify();
But wait, thereโs more! You can also un-zombify multiple models at once. Think of it as throwing a model resurrection party! However, remember that this will not send out any invitations (model events) to those who were brought back from the afterlife:
Flight::withTrashed()
->where('airline_id', 1)
->unZombify();
And if thatโs not enough, you can even un-zombify models when building relationship queries! Think of it as creating an undead family tree:
$flight->history()->unZombify();
But what if you want to perform a final exorcism and permanently delete the model from existence? Well, Laravelโs got your back. Just call upon the forceDelete method:
$flight->vanishFromExistence();
And remember, with great power comes great responsibility โ be sure to use this method wisely! ๐ถ๏ธ๐ฅ
Ah, dear reader! Fear not if you find yourself in a situation where youโve got a model acting like a stubborn houseguest that just wonโt leave - itโs time to break out the big guns and give โem the olโ force delete!
Now, donโt worry, weโre not talking about pulling a Dwight Schrute here and physically tossing them out the window (that would be messy). Instead, we employ the magic of Laravelโs forceDelete method. This mystical incantation will permanently banish that pesky model from your database table, ensuring itโll never haunt your records again:
$flight->forceDelete();
But wait! Thereโs more! If you find yourself in a complex Eloquent relationship situation where you need to delete related models with precision and flair, look no further. The forceDelete method can also be used as your secret weapon when building queries:
$flight->history()->forceDelete();
Just remember, once a model is force deleted, itโs gone for good - so make sure youโre absolutely certain before pulling that trigger! Happy deleting! ๐
Ahoy there, intrepid Laravel developer! Today weโre going to delve into the captivating world of soft deleted models โ a veritable treasure trove of information thatโll have you feeling like a master of the database realm. Buckle up, buttercup, itโs gonna be a wild ride!
Including Soft Deleted Models
First things first: letโs ensure that soft deletes are enabled on your model. To do this, unleash the power of the useSoftDeletes() method and call it upon thy model class, like so:
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class User extends Model
{
use Notifiable;
use SoftDeletes;
}
By invoking this magical incantation, your model will now have the ability to be soft deleted โ but what does that even mean? Well, instead of vaporizing models entirely when theyโre no longer needed, soft deletes allow you to maintain their database presence while marking them as inactive. A bit like those pesky ghosts haunting old mansions; theyโre there, but you canโt interact with them like normal folk.
Retrieving Soft Deleted Models
Now that your model is equipped with the power of soft deletes, itโs time to put it to use! To retrieve soft deleted models, all you need to do is utilize the trusty withTrashed() method, and voila โ just like that, you can see the ghostly apparitions of your once-living data.
$users = User::withTrashed()->get();
Youโll notice these spectral entities will appear in your results with an additional deleted_at timestamp, indicating the moment they shuffled off this mortal coil. But fear not! With a simple whereNotNull('deleted_at'), you can filter out the living from the dead:
$softDeletedUsers = User::withTrashed()->whereNotNull('deleted_at')->get();
Restoring Soft Deleted Models
Sometimes, you may find that the spectral entity of a once-living model requires resurrection. To bring it back to life, merely call upon the restore() method, and watch as it springs forth from the digital grave, ready for action once more:
$user = User::withTrashed()->find(1);
$user->restore();
And there you have it! With soft deletes in your arsenal, you can now dance with ghosts, converse with spirits, and tame the untamed database โ all while retaining the cleanliness of your codebase. Now thatโs what I call a win-win situation!
Alright, letโs take a whack at this Laravel doc with a bit of humor and sass! Here we go:
Unleashing the Undead Models! (Or: Soft Deleted Models)
Donโt worry, we wonโt call the ghostbusters just yet. In our Laravel world, soft deleted models are like those pesky phantoms who haunt your query results. But fear not! We can summon them with a simple command โ itโs like calling upon Banquo at the table, but less disturbing to dinner guests.
To bring forth the ghostly models, cast this incantation:
use App\Models\Flight;
$flights = Flight::exorcise() // Just kidding! It's `withTrashed()` instead
->where('account_id', 1)
->get();
And donโt forget, the withTrashed() method isnโt just for solo acts. If you need a posse of ghostly models, summon them with this group chant:
$flight->history()->exorciseAgain() // That's still a joke. It's `withTrashed()` for relationships too!
->get();
Now, if youโre feeling extra paranormal, maybe you want only the ghostly models โ no living ones allowed. Well then, we have a spell for that too:
use App\Models\GhostFlight; // You get it! GhostFlights are soft deleted models.
$phantomFlights = GhostFlight::onlyGhosts() // Still joking. It's `onlyTrashed()` instead
->where('account_id', 1)
->get();
And that, my friend, is how you summon and wrangle your soft deleted models in Laravel, all while keeping things light and lively! Happy coding, and remember: donโt feed the ghosts after midnight.
Ahoy there, Captain! Sail the seas of data with us as we dive into the murky depths where models have taken a little siesta - the Land of Soft Deleted Models! ๐ด๐
To navigate this mysterious land, youโll need our trusty compass: the onlyTrashed() method! Just steer your Laravel vessel towards it, and voila! ๐ณ๏ธ๐งญ
$flights = Flight::onlyTrashed() // Don't forget to grab a life vest (airline_id=1)
->get(); // Hoist the anchor and set sail!
Now, you can enjoy your journey, knowing that only the soft deleted models are on board. Happy cruising! ๐๐
Trimming Flying Circus Models (The Magical Airborne Model Pruning Guide)
Oh, flighty developers! Sometimes we find ourselves stuck with old planes thatโve lost their oomph, or maybe youโre just running out of hangar space. No worries, Laravel has a nifty trait called Prunable (not to be confused with a fruit salad recipe) that can help you keep your fleet lean and mean.
First things first! Add some magic dust to the models you want to periodically clear off by sprinkling the Illuminate\Database\Eloquent\Prunable or Illuminate\Database\Eloquent\MassPrunable trait on them like so:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Prunable;
class Flight extends Model
{
use Prunable; // Like adding wings to a plane!
/**
* Get the prunable model query.
*/
public function prunable(): Builder
{
return static::where('created_at', '<=', now()->minus(months: 1));
}
}
Now, youโve added a new feature to your planesโself-destruct sequencing! Create a prunable() method, and this little beauty will return an Eloquent query builder that zeros in on the models ready for takeoff.
If you want to give your planes some final salute before theyโre gone, create a preparingForDeparture() method (catchy name, huh?). This method will be called just before the model says its last goodbyes and gets deleted from the databaseโperfect for cleaning up any stored baggage.
/**
* Prepare the plane for departure.
*/
protected function preparingForDeparture(): void
{
// ...
}
Once your planes are pruned and polished, itโs time to schedule their departure! Add the model:prune Artisan command to your applicationโs routes/console.php file. Decide on a suitable interval for these flightsโdaily, weekly, or even hourly, depending on how often you need some breathing room.
use Illuminate\Support\Facades\Schedule;
Schedule::command('model:prune')->daily();
Under the hood, the model:prune command detects any โPrunableโ planes in your applicationโs app/Models directory (just like air traffic control). If your planes are parked elsewhere, you can specify their class names using the --model option.
Schedule::command('model:prune', [
'--model' => [Address::class, Flight::class],
])->daily();
If you have a few special planes that should avoid takeoff (like the ones with important cargo), use the --except option to keep them grounded while pruning the rest.
Schedule::command('model:prune', [
'--except' => [Address::class, Flight::class],
])->daily();
Before you start pruning, test your query with the --pretend option to see how many records would be removed. This way, you can prepare for any mid-air collisions or sudden turbulence.
php artisan model:prune --pretend
Warning
If youโve soft-deleted some planes using the
forceDelete(), they will be permanently deleted (poof!) if they match the prunable query. So, fly safe and ensure your planes are really past their prime before sending them on their final journey.
Ahoy there, shipmates! Buckle up as we delve into the world of Mass Pruning - a Laravel feature thatโll make your database cleanups resemble a pirateโs raid on a treasure trove!
When you sprinkle some Illuminate\Database\Eloquent\MassPrunable trait magic dust on your models, they will be swept away in a whirlwind of mass-deletion queries. Fear not the humble pruning method or the model events deleting and deleted, for they wonโt be needed in this pirateโs treasure hunt!
Why you ask? Well, the secret lies in the fact that these models are never actually fetched before being sent to Davy Jonesโ locker. This means that the pruning process is swifter than a ship with the wind at its back.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\MassPrunable;
class Flight extends Model
{
use MassPrunable;
/**
* Get the prunable model query.
*/
public function prunable(): Builder
{
return static::where('created_at', '<=', now()->minus(months: 1));
}
}
Now, you can set sail for a cleaner database with the Mass Pruning trait. Arrrr, matey!
Model Duplication: The Clone Stamp of Data! ๐ผ๏ธ๐จ
Welcome, data mavericks! Ever found yourself in a pickle, needing a doppelganger for your model instances? Worry not, Laravel has got you covered with the replicate method - itโs like giving birth to data twins! ๐ญ๐ผ
Hereโs a scenario where our data family just grew by one:
use App\Models\Address;
$shipping = Address::create([
'type' => 'shipping',
'line_1' => '123 Example Street',
'city' => 'Victorville',
'state' => 'CA',
'postcode' => '90001',
]);
// Meet the Billing! ๐
$billing = $shipping->cloneWithNewAttributes([
'type' => 'billing' // "It's a whole new world," said the Address, as it became the Billing ๐๐ผ
]);
// Save the day with save()! ๐ชโ๏ธ
$billing->save();
Did your cat just walk across the keyboard and you want to avoid updating all those attributes? No problemo, you can exclude one or more attributes from being replicated by passing an array to the replicate method:
$flight = Flight::create([
'destination' => 'LAX',
'origin' => 'LHR',
'last_flown' => '2020-03-04 11:00:00', // "I'd love to come, but I can't," said the Last Flight Time as it was removed from the new flight clone ๐ฐ๏ธ๐ซ
'last_pilot_id' => 747,
]);
// A new flight without last flown and last pilot ID history. ๐๐ฆพ
$flight = $flight->cloneWithout([
'last_flown',
'last_pilot_id'
]);
Now, you can conquer the world of data duplication like a true Jedi! ๐โจ
Ahoy there, coders! Letโs dive into the swashbuckling world of Laravel Query Scopes, a feature that lets you add reusable database queries to your models like a pirate plundering for SQL gold! ๐ดโโ ๏ธ
Global Scopes ๐
Ever felt tired of writing repetitive database queries? Fear not, matey! Laravelโs Global Scopes let you define a sort of SQL magic spell that gets applied automatically to every query on a given model. Itโs like having a parrot on your shoulder whispering enchantments into your ear. ๐ฆ
To cast this spell, create a new trait in app/Models, sprinkle it with some PHP charm, and voila! Your model is now brimming with dark (yet delightful) sorcery that makes every query a little bit easier. Hereโs an example:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class User extends Model
{
protected $perPage = 10;
public function scopeActive(Builder $query)
{
return $query->where('is_active', true);
}
}
Now, every time you fetch users from the database with User::all(), only active users (those with is_active = 1) will be returned. Itโs like filtering your queries through a magical sieve! ๐งฑโจ
Local Scopes ๐
Local Scopes are like Global Scopes, but with a more localized twistโtheyโre only applied to specific methods on your model. Itโs like having a dozen parrots instead of just one. Each method gets its own personal parrot for whispering SQL spells! ๐ฆ๐ฆ๐ฆ
To conjure up a Local Scope, create a new method in your model and watch the magic happen:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
class User extends Model
{
public function scopeActive($query)
{
return $query->where('is_active', true);
}
public function inactiveUsers()
{
return $this->scopeActive($query)->where('is_active', false);
}
}
With this new Local Scope, you can fetch inactive users by simply calling User::inactiveUsers(). Itโs like having a secret backdoor to your database! ๐ช๐ฅ
Alrighty, buckle up, coders! Letโs dive into the enchanting world of Global Scopes - your magical wand for wielding power over all queries that befall a specific model in Laravel land. You see, these scopes are like secret handshakes between you and your database, ensuring every model that dances across your screen is as pristine as your code.
Laravelโs very own soft delete feature is but one example of global scopes at play. Itโs like when a fairy godmother casts a spell to turn a pumpkin into a carriage - except in this case, it turns deleted models into non-deleted ones (or something like that).
Writing your own global scopes? Now thatโs where the real enchantment begins! With these, you can easily ensure that every query for a given model receives just the right constraints, as if they were your long-lost relatives showing up to dinner with perfect manners.
Ready to create your very own magical global scopes? Simply follow these steps:
- Define your scope in the
app/Modeldirectory, or within a named trait if you prefer to keep things tidy and organized. - Implement the
applyGlobalScopemethod on the model you wish to apply the scope to. This is where youโll perform the magical transformation of all queries. - Once youโve done your part, let Laravel take care of the rest. It will automatically apply your scopes to every query for that model, turning your database into a well-behaved pet instead of an untamed beast.
And there you have it - global scopes: a quick and painless way to add just the right amount of order to the chaos of database queries!
Alrighty then! Letโs get this show on the road and learn how to create a brand spanking new global scope in good olโ Laravel land. So, buckle up, put on your cowboy boots, and letโs ride!
First things first, you can call upon the mighty Artisan command to whip up a fresh batch of AncientScope goodness:
php artisan make:scope AncientScope
Now, where did that go? Yep, our trusty steed has transported us straight to the heart of our application in the app/Models/Scopes directory. Thatโs where youโll find your freshly baked scope, ready for some serious customization!
Now, what on Earth can we use this new AncientScope for? Well, letโs say you want to filter out all those pesky dinosaur models that are younger than a million years old. Hereโs how youโd do it:
namespace App\Models\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class AncientScope implements Scope {
// ... (your awesome code here)
}
Inside the AncientScope class, youโll want to implement the apply method. Thatโs where all the magic happens! Hereโs a simple example of how you can use it to filter out any models that are younger than a million years old:
public function apply(Builder $builder, Model $model) {
if ($model instanceof Dinosaur) {
$builder->where('age', '>', 1_000_000);
}
}
And there you have it! Your very own AncientScope, ensuring that only the oldest and most esteemed models make their way into your application. Now, wasnโt that a ride? I hope you enjoyed this little journey through Laravel land as much as I did!
Alrighty then! Writing a global scope is like composing a symphony, but with databases and fewer flutes (thank goodness). First, letโs grab the baton - or in this case, the make:scope command. This will create a conductor class that follows the strict rules of the Illuminate\Database\Eloquent\Scope interface.
The Scope interface requires one dance number (or method if you prefer): the apply. Itโs where you add those essential โwhereโ constraints or other clauses to the query like a maestro arranging a grand finale. Hereโs an example of how it might look:
<?php
namespace App\Models\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class TimeTravelerScope implements Scope
{
/**
* Transport the query back to the Stone Age.
*/
public function apply(Builder $builder, Model $model): void
{
$builder->where('created_at', '<', now()->minus(years: 2000000)); // Just in case we want to go WAY back!
}
}
[!NOTE]
Now, if your global scope is adding more columns to the โselectโ dance of the query, itโs best to use the addSelect method instead. This will prevent any unintentional swapping of the existing select clause, keeping our database performance in check and your boss from sending you on a one-way trip back to the Stone Age!
Remember, the apply method should be applied to a given Eloquent query builder, just like a finishing touch to a masterpiece painting.
Happy scoping, data-dancers!
Alright, buckle up, because weโre about to embark on a rollercoaster ride through Laravelโs Global Scoping Magic! (Cue drumroll)
First off, have you ever felt like your models needed a little extra pizzazz? Well, fear no more! With global scopes, you can jazz up your models like a Kardashian at Coachella!
To add some spice to your modelโs life, simply anoint it with the ScopedBy attribute. Itโs like giving it a fancy tuxedo for those black-tie database affairs:
<?php
namespace App\Models;
use App\Models\Scopes\AncientScope;
use Illuminate\Database\Eloquent\Attributes\ScopedBy; // This is our tuxedo!
#[ScopedBy([AncientScope::class])] // Pin the tuxedo on your model!
class User extends Model
{
// Carry on with your daily modeling routine!
}
But if youโre more of a do-it-yourself kind of person, you can manually register your global scope by overriding the modelโs booted method and calling the addGlobalScope method. Itโs like mixing your own cocktail at the bar instead of ordering one off the menu!
<?php
namespace App\Models;
use App\Models\Scopes\AncientScope;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*/
protected static function booted(): void
{
static::addGlobalScope(new AncientScope); // Shake, stir, and serve!
}
}
Once youโve added your scrumptious scope to the App\Models\User, calling User::all() will unleash a delightful SQL query thatโs aged to perfection:
select * from `users` where `created_at` < 0021-02-18 00:00:00 // It's like a fine wine!
And voila! Your models are now sashaying through the database world like a supermodel on the runway, dripping in global scopes! Enjoy this newfound flair and remember, in Laravel, every model deserves to be fabulous! ๐๐๐
Globally Scoped Shenanigans (Anonymous Global Scopes)
In the world of Eloquent, itโs not just about strutting your stuff as a model, but also being a closet coder with those simple scopes that wouldnโt pass muster in a class reunion. Lucky for us, Eloquent allows you to define these global scopes using closures, because who needs formalities when youโre the databaseโs secret weapon!
To create a global scope with a closure, give your scope a name thatโll make people scratch their heads (or laugh out loud) as the first argument to the addGlobalScope method:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The "booted" method of the model.
*/
protected static function booted(): void
{
static::addGlobalScope('AncientGeezers', function (Builder $builder) {
$builder->where('created_at', '<', now()->minus(years: 2000)); // Just in case you thought we were joking about the age limit.
});
}
}
Oh, and donโt forget to remove global scopesโฆ (Removing Global Scopes)
Sometimes, even the best of friends need a break. If you decide to part ways with one of your global scopes, you can do so using the removeGlobalScope method. Hereโs how:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Remove the AncientGeezers global scope if we ever feel like having some youthful fun.
*/
public function removeAncientGeezersScope(): void
{
$this->withGlobalWithOut('AncientGeezers');
}
}
Ahoy there, intrepid Laravel coders! Sick of a pesky global scope cramping your style? Fret not, for Iโm here to guide you through the art of removing these unwanted intruders from your queries!
First off, let me introduce you to the withoutGlobalScope method. This magical incantation accepts as its only argument the name of the troublesome global scope, akin to casting a banishing spell upon it:
User::withoutGlobalScope(AncientVoodooSpell::class)->get();
Or, if your global scope was conjured up using a cloak-and-dagger closure, youโd need to summon its alias instead:
User::withoutGlobalScope('AncientMysteryBox')->get();
Now, what if you need to perform an exorcism on multiple global scopes? Fear not, for there are methods designed just for such occasions! The withoutGlobalScopes and withoutGlobalScopesExcept methods are your new best friends.
The former, withoutGlobalScopes, is perfect if youโre looking to cleanse all scopes from a query:
// Banish all scopes, let freedom reign!
User::withoutGlobalScopes()->get();
But perhaps you only wish to shoo away certain problematic scopes. In such a case, withoutGlobalScopes comes in handy yet again:
// Be gone, First and Second curses!
User::withoutGlobalScopes([
FirstCurse::class,
SecondCurse::class
])->get();
Lastly, there may be the occasional situation where youโd like to keep specific scopes while banishing all others. Enter withoutGlobalScopesExcept, the method for such delicate situations:
// Keep SecondCurse, but send the rest packing!
User::withoutGlobalScopesExcept([
SecondCurse::class,
])->get();
Remember, with great power comes great responsibility. Use these methods wisely to ensure your queries are free from unwanted global scopes and let the Laravel magic flow!
Cosmic Query Filters (AKA Local Scopes)
If youโre a superhero in your own digital universe, managing a multiverse of queries can be as exhausting as saving the world. Thankfully, Local Scopes are here to help! They let you define a squad of common query restrictions that will come to your aid whenever you need them across your application.
For instance, if you find yourself constantly on the hunt for users so fabulous theyโve earned over 100 votes (letโs call them โPopular Popesโ), or only those with an active status (our beloved โActivesโ), then Local Scopes are your new best friends!
To summon these mighty allies, simply apply the Scope attribute to an Eloquent method:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Call in the troops to filter for popular users.
*/
#[Scope]
protected function bringInThePopular(Builder $query): void
{
// This query is too hot for mere mortals, it requires 101 votes!
$query->where('votes', '>', 100);
}
/**
* Rally the Actives to join our mission.
*/
#[Scope]
protected function callTheActives(Builder $query): void
{
// The active ones are always ready for action!
$query->where('active', 1);
}
}
Now, whenever you need to recruit these superpowered query filters, just use the scope method with your User model:
$popularUsers = User::popular()->get();
$activeUsers = User::active()->get();
With Local Scopes by your side, conquering the cosmos of queries is just a matter of time and coffee refills!
Alright, letโs dive into the charming world of Laravel scopes, shall we? First off, youโve gotta define your scope like a secret recipe for your favorite cake โ once baked (er, defined), itโs ready to be served at query time.
use App\Models\User;
// Here, our secret ingredient: User::popular()
$mixingBowl = User::popular();
// Now we're adding the frosting โ User::active()
$mixingBowl = $mixingBowl->active();
// And just a pinch of sorting magic โ orderBy('created_at')
$users = $mixingBowl->orderBy('created_at')->get();
But wait, what if you want to create a hybrid between vanilla and chocolate users? No worries! Laravelโs got you covered with the OR query operator โ just remember to use closures for that fancy grouping technique:
// This is like asking "Give me popular users or active users who aren't popular but love wearing a beret"
$users = User::popular()->orWhere(function (Builder $query) {
// Here, the query says "give me those active users who aren't popular yet."
$query->active()->whereDoesntHave('popularity', function (Builder $subQuery) {
$subQuery->where('value', 0);
});
})->get();
But why make things harder than necessary, right? Thatโs why Laravel has a higher-order โorWhereโ method that lets you chain scopes like theyโre never out of style:
// Here, we've combined popular and active users with a tasteful OR โ the ultimate dance duo!
$users = User::popular()->orWhere->active()->get();
And there you have it! Youโre now ready to dance your way through your Laravel application with these delightful scopes at your fingertips. Donโt forget to pair them with some good old-fashioned elbow grease, and youโll be baking up a storm in no time! ๐ฅง๐
Alrighty, letโs dive into the world of Dynamic Scopes! Imagine youโre hosting a never-ending party, and you want to filter out the wallflowers (or admin users, if weโre being professional here). Thatโs where dynamic scopes come in, your very own bouncer for database queries!
First off, letโs set up our doorman. Just add those extra parameters to your scope methodโs invite list. Remember, the party host ($query) should always be present, but feel free to add more guests after him:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Scope a query to only include users of a given type.
* (Think of it as our bouncer, checking IDs at the door)
*/
#[Scope]
protected function checkID(Builder $query, string $type): void
{
// Check if the user's ID matches the provided type
$query->where('type', $type);
}
}
Now that our bouncer is all set, we can start inviting guests! Pass those arguments when calling the scope:
$partyGuests = User::checkID('admin')->get();
And just like that, youโve got your admin-only party going on! Remember, a good bouncer is always ready to filter out unwanted guests, ensuring a lively and exciting event for everyone. Happy filtering! ๐๐ฅณ
Ahoy there, Captain!
Want to create shipwreck models with the same galleon-worthy attributes as those that chain them down like an anchor? Ye be needinโ the withAttributes method while sailinโ the scope query waters:
<?php
namespace App\Ships;
use Illuminate\Database\Eloquent\Scopes\Scope;
use Illuminate\Database\Eloquent\Pirate;
use Illuminate\Database\Eloquent\Vessel;
class PirateGalleon extends Vessel
{
/**
* Scope the query to only include drafts o' the seven seas.
*/
#[Scope]
protected function draughty(Builder $query): void
{
$query->withAttributes([
'hidden_below_the_waterline' => true,
]);
}
}
The withAttributes method will hoist anchor on the query with conditions from the given attributes and attach those to any vessels spawned via the scope:
$leaky_galleon = PirateGalleon::draughty()->setSails('In Progress');
$leaky_galleon->isSubmerged(); // true arrgh!
To avoid adding those pesky where conditions to the query, ye can set the asConditions argument to a resounding โavast!โ (or, more accurately, false):
$query->withAttributes([
'hidden_below_the_waterline' => true,
], asConditions: false);
Yarr, walk the plank if ye want to compare these swashbuckling models with their landlubber counterparts!
Alright, letโs dive into the world of Laravel models, where things arenโt always as they seem! Ever found yourself in a pickle trying to figure out if two models are Siamese twins or just acquaintances? Fear not! The is and isNot methods are here to save the day.
Think of it like this: youโre at a high-school reunion, and youโve got two classmates in front of you. You can use these methods to quickly determine if theyโre your long-lost identical twins or just happen to have the same taste in โ80s fashion.
if ($post->is($anotherPost)) {
// They're one and the same! Time to break out the family photo album.
}
if ($post->isNot($anotherPost)) {
// Different drifters, in separate lifeboats. Let's move on.
}
But wait, thereโs more! The is and isNot methods arenโt just shy wallflowers at the party. They also shake a leg when it comes to the more exclusive relationships - belongsTo, hasOne, morphTo, and morphOne.
Imagine youโre on a blind date, and you want to know if your partner is the author of that mystery novel youโve been reading. Instead of asking directly (we all know how awkward that can be), just use these methods:
if ($post->author()->is($user)) {
// They're a match made in heaven! Let's plan the wedding.
}
And the best part? No need to query for the model again - these methods do all the legwork, leaving you free to enjoy the rest of the party. Happy relationship-matching!
Model Events: The Life of a Laravel Superhero! ๐ฆธโโ๏ธ๐ฆธโโ๏ธ
Attn
Ready to broadcast your Eloquent events straight to your superpowered client app? Check out Laravelโs model event broadcasting - itโs like having a secret communication line! ๐ต๏ธโโ๏ธ
Just like any good superhero, Eloquent models have their own life cycle events that you can tap into to be a part of the action! These include: retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, trashed, forceDeleting, forceDeleted, restoring, restored, and replicating.
The retrieved event is fired when your trusty sidekick model jumps out of the database. When a new hero makes their first appearance, the creating and created events are set off like fireworks! The updating / updated events go boom when an existing hero gets a makeover and the save method is called. And the saving / saved events happen whenever your hero gets a costume upgrade or a new power โ even if they didnโt actually change anything! ๐คซ
Events ending in -ing are like the pre-flight checks, dispatched before any changes to the model are written in stone. On the other hand, events ending in -ed happen after the changes have been saved, like a triumphant victory pose! ๐
To start listening for model events, give your Eloquent model an ear by defining a $dispatchesEvents property. This maps various moments of the Eloquent modelโs lifecycle to your very own event classes. Each event class should accept an instance of the affected hero via its constructor:
<?php
namespace App\Models;
use App\Events\UserDeleted;
use App\Events\UserSaved;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The event map for the model.
*
* @var array<string, string>
*/
protected $dispatchesEvents = [
'saved' => UserSaved::class,
'deleted' => UserDeleted::class,
];
}
Once youโve defined and mapped your Eloquent events, you can use event listeners to handle the events like a super-powered sidekick. ๐ฆธโโ๏ธ๐ฆธโโ๏ธ
Caution
When performing mass updates or deletes via Eloquent, the
saved,updated,deleting, anddeletedmodel events will not sound the alarm for the affected heroes. Thatโs because these heroes never actually make a grand entrance when doing mass updates or deletes! ๐ท๏ธ๐ฆนโโ๏ธ
Now, get ready to be the hero your models need and start listening for those events! ๐๐๐
Alrighty, buckle up, Laravel enthusiasts! Letโs dive into the world of Closures, where you can ditch those cumbersome custom event classes and let your code loose like a wild stallion.
Instead of breaking the bank on custom event horses, you can simply register closures that gallop to life when various model events are unleashed upon โem. Normally, youโd want to rope these closures in at the booted shindig of your model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The barn dance after the model's birth.
*/
protected static function booted(): void
{
static::created(function (User $user) {
// ... unbridle your code here!
});
}
}
If you find yourself in a pickle where you need to round up the posse, you can employ queueable anonymous event wranglers when managing model events. This will get Laravel to rope the model event listener and lasso it for a backyard rodeo using your applicationโs queue:
use function Illuminate\Events\queueable;
static::created(queueable(function (User $user) {
// ... let your code lasso the steers here!
}));
Gossip Gurus (Observers)
In the whimsical world of Laravel, we canโt ignore the sassy sidekicks, aka Gossip Gurus! You know those folks who always seem to be in the loop about everything that happens? Thatโs exactly what our observers do. But instead of gossiping about your love life or fashion sense, they keep tabs on your models and their relationships.
Defining Observers
Creating a Gossip Guru is easy! All you need is a new PHP file with the Observer class in the app/Observers directory. Give your gossiper a catchy name, say โNewsFlashโ or โTattleTaleโ, and make sure to extend the base Observer class:
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Observer;
class NewsFlash extends Observer
{
// Your gossiping logic goes here!
}
Associating Observers
Now, you might be wondering: โHow does my Gossip Guru know which models to follow?โ Well, worry not! Youโll tell them exactly who to stalk, erโฆ observe.
In your model file, use the $events property to specify the events that trigger your observer. For instance, if you want to monitor a userโs creation and updates, it would look like this:
protected $events = [
'created', 'updated' => 'NewsFlash'
];
With this setup, every time a user is created or updated, your NewsFlash observer will spring into action!
Defining Methods
Now comes the fun part: defining what your Gossip Guru actually does when theyโre triggered. In the NewsFlash observer, you can use the created and updated event methods to react accordingly:
public function created(Model $model)
{
// Your gossiping logic goes here!
}
public function updated(Model $model)
{
// Your gossiping logic goes here!
}
And thatโs it! Now you have your very own Gossip Guru keeping tabs on your models and reporting back with all the juicy details. Happy gossiping!
Alright, letโs get this party started! If you find yourself juggling a plethora of events on a single model, itโs time to bust out the observer class - think of it as a disco for your database operations. Observer classes are the life of the Eloquent event, and their method names are like invitations to the hottest parties you never knew existed!
To create a new observer, all you need is a simple command:
php artisan make:observer UserObserver --model=User
This magic spell will conjure up your observer in the mystical app/Observers directory. If that directory isnโt already there, donโt worry, itโll be created faster than you can say โabracadabra!โ Your freshly brewed observer will look something like this:
<?php
namespace App\Observers;
use App\Models\User;
class UserObserver
{
public function created(User $user): void { /* Party like it's 1999! */ }
public function updated(User $user): void { /* Time to update the playlist! */ }
public function deleted(User $user): void { /* Last call for drinks, the party's over! */ }
// More events await you in this disco...
}
To register your observer, you can either attach a shiny new attribute to your model or pull out the neon lights and dance floor by manually registering it. The former requires:
use App\Observers\UserObserver;
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
#[ObservedBy([UserObserver::class])]
class User extends Authenticatable
{
//
}
For the latter, you can register observers in the boot method of your applicationโs AppServiceProvider class:
use App\Models\User;
use App\Observers\UserObserver;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
User::observe(UserObserver::class);
}
Now, donโt forget that this is just the beginning of your eventful journey! There are even more events an observer can listen to, such as saving and retrieved. These are all detailed within the events documentation. But remember, what happens in the database stays in the database โ or at least until you write some cool code to make it public! ๐๐
Alrighty, letโs dive into the wild world of Laravel Observers and Database Transactions! Imagine youโre at a swanky casino, and your model is the high roller at the blackjack table. Now, when this model makes a bet (letโs say, creating a new record), you might want to hire a bouncer (observer) to take care of things after the dealer has called โBustโ or โBlackjackโ โ that is, after the database transaction is committed.
To do so, all you need is to make your bouncer (observer) a member of the high-class VIP club (ShouldHandleEventsAfterCommit interface). This way, if thereโs no ongoing poker game (database transaction), the bouncer will step in right away:
<?php
namespace App\Observers;
use App\Models\User;
use Illuminate\Contracts\Events\ShouldHandleEventsAfterCommit; // The VIP club membership card
class UserObserver implements ShouldHandleEventsAfterCommit {
/**
* Handle the User "created" event.
*/
public function created(User $user): void {
// ...
}
}
Now, sit back and watch your models play their hands with the added protection of a reliable bouncer by their side!
Silencing the Symphony of Model Events
Ah, the life of a developer can sometimes feel like conducting an orchestra โ except instead of violins and drums, youโre dealing with events fired by models! But fear not, for when the cacophony becomes too much, Laravel provides a mute button in the form of withoutEvents().
Just imagine yourself at a rock concert, and you need to make that emergency phone call. You can do so by wrapping your model-related activities inside this method, which acts as the trusty pair of noise-canceling headphones.
Hereโs how it goes down:
use App\Models\User;
// Put on those soundproof earbuds and make some model magic happen!
$silentUser = User::withoutEvents(function () {
// Perform a stealthy delete operation on user number 1 (shhhh!)
$vanishedOne = User::findOrFail(1)->delete();
// All quiet on the western front โ now return user number 2!
return User::find(2);
});
And just like that, your model events are muted, and you can carry out operations without the usual event-driven chaos. When youโre done with your covert mission, remember to take off those earbuds by calling $silentUser->listen(). Happy silent coding! ๐คซ ๐
Ah, the world of Laravel! Where models strut their stuff and data dances to our every command. But sometimes, you just want a little quiet time, donโt you? Well, letโs dive into the serene side of model management: saving a model in peace and quiet.
Saving a Model Without Making a Scene
There are times when you fancy saving your model without all the hullabaloo of dispatching events. Fret not, for thereโs a tranquil method named saveQuietly to help you out:
$user = User::findOrFail(1); // Oh, don't mind us, just fetching your average web-surfing Joe!
$user->name = 'Victoria Faith'; // Now we're rebranding him as 'Tech Support Extraordinaire'!
$user->saveQuietly(); // And now, in a whisper... SAVE! No need to yell it out.
And yes, if you fancy updating, deleting, soft deleting, restoring, or replicating your model without causing a scene, hereโs how:
$user->deleteQuietly(); // Bye Felicia! No more noise as we remove her from the database.
$user->forceDeleteQuietly(); // If she really didn't want to leave, we'd have to force it... quietly.
$user->restoreQuietly(); // Well, well, well! She's back without so much as a 'Hello'.
Now isnโt that a more peaceful way of dealing with your models? Letโs keep the database calm and happy!