Kontynuacja poprzednich lekcji – dalej poznajemy Laravela i jego możliwości, w tym ORM, bazy danych, kolekcje. Do dzieła.
Poprzednio napisaliśmy takie coś:
Artisan::command('first-where-age {age}', function (int $age) {
$person = Person::firstWhere('age', $age);
$this->comment("Name: {$person->firstName} {$person->lastName}");
$this->comment("Age: {$person->age}");
$this->comment("Created at: {$person->created_at}");
});
Problem z tym taki, że jak nie mamy osobnika o takim wieku to program się wysypie. Ok, pierwsze podejście:
Artisan::command('first-or-age {age}', function (int $age) {
$person = Person::where('age', $age)->firstOr(function(){
return -1;
});
if($person === -1){
$this->comment("No matching results for age $age");
} else {
$this->comment("Name: {$person->firstName} {$person->lastName}");
$this->comment("Age: {$person->age}");
$this->comment("Created at: {$person->created_at}");
}
});
firstOr bierze pierwszego pasującego albo wykonuje callback. Inne podejście to firstOrFail:
Artisan::command('findOrFail-age {age}', function (int $age) {
try{
$person = Person::where('age', $age)->firstOrFail();
$this->comment("Name: {$person->firstName} {$person->lastName}");
$this->comment("Age: {$person->age}");
$this->comment("Created at: {$person->created_at}");
}
catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
$this->comment("No matching results for age $age");
}
});
Przypomnijmy sobie funkcje, którymi liczyliśmy osobników powyżej 25 lat:
Artisan::command('count-above-25', function () {
$count = Person::where('age', '>', 25)->count();
$this->comment("Number of people above 25 in db: $count");
});
Artisan::command('count-above-25-db', function () {
$count = DB::table('people')
->where('age', '>', 25)->count();
$this->comment("Number of people above 25 in db: $count");
});
Teraz poznamy reject, bardzo ciekawą funkcję do użycia na kolekcjach:
Artisan::command('count-above-25-reject', function () {
$people = Person::all();
$peoplecnt = $people->count();
$above25 = $people->reject(function($person){
return $person->age <= 25;
});
$above25cnt = $above25->count();
$below25cnt = $people->diff($above25)->count();
$this->comment("Number of all ppl in db: $peoplecnt");
$this->comment("Number of people above 25 in db: $above25cnt");
$this->comment("Number of people below or eq 25 in db: $below25cnt");
});