Generating PDF contracts in Laravel: DomPDF vs Spatie/Browsershot?
I’m building a small app in Laravel to generate and sign contracts.
For the PDF version of those contracts I’ve always used barryvdh/laravel-dompdf and it’s been “good enough”.
Lately I’m seeing more people using Spatie’s Browsershot / laravel-pdf for PDFs.
For a contracts use case (multi-page, decent layout, mostly text with some branding), would you stick to DomPDF or move to Browsershot?
Any real-world pros/cons in terms of CSS support, performance or server setup that I should consider?
https://redd.it/1qa6hgh
@r_php
I’m building a small app in Laravel to generate and sign contracts.
For the PDF version of those contracts I’ve always used barryvdh/laravel-dompdf and it’s been “good enough”.
Lately I’m seeing more people using Spatie’s Browsershot / laravel-pdf for PDFs.
For a contracts use case (multi-page, decent layout, mostly text with some branding), would you stick to DomPDF or move to Browsershot?
Any real-world pros/cons in terms of CSS support, performance or server setup that I should consider?
https://redd.it/1qa6hgh
@r_php
Reddit
From the laravel community on Reddit
Explore this post and more from the laravel community
A Week of Symfony #993 (January 5–11, 2026)
https://symfony.com/blog/a-week-of-symfony-993-january-5-11-2026?utm_medium=feed&utm_source=Symfony%20Blog%20Feed
https://redd.it/1q9vid2
@r_php
https://symfony.com/blog/a-week-of-symfony-993-january-5-11-2026?utm_medium=feed&utm_source=Symfony%20Blog%20Feed
https://redd.it/1q9vid2
@r_php
Symfony
A Week of Symfony #993 (January 5–11, 2026) (Symfony Blog)
This week, Symfony development activity focused on fixing bugs and updating tests to make them compatible with the newest PHPUnit versions. Meanwhile, the upcoming Symfony 8.1 release started adding n…
My highlights of things for PHP to look forward to in 2026
https://stitcher.io/blog/php-2026
https://redd.it/1qatqzj
@r_php
https://stitcher.io/blog/php-2026
https://redd.it/1qatqzj
@r_php
stitcher.io
A blog about modern PHP, the web, and programming in general. Follow my newsletter and YouTube channel as well.
Why is something like PHP-FPM necessary in PHP, but not in other languages such as JS (nodejs) or Go lang?
I want to deploy my PHP website on my VPS and thought it would be simpler. I use NGINX as a reverse proxy, and if I want to connect it to PHP, it seems I need something like PHP-FPM, which has several configurations that overwhelm me.
I saw that PHP has a built-in server, but apparently it's only for development and is not recommended for production use. In other environments such as NodeJS or Golang, I don't see the need for another tool like php-fpm. Am I missing something? Maybe there's a simpler way without all the configuration hassle?
https://redd.it/1qagk8i
@r_php
I want to deploy my PHP website on my VPS and thought it would be simpler. I use NGINX as a reverse proxy, and if I want to connect it to PHP, it seems I need something like PHP-FPM, which has several configurations that overwhelm me.
I saw that PHP has a built-in server, but apparently it's only for development and is not recommended for production use. In other environments such as NodeJS or Golang, I don't see the need for another tool like php-fpm. Am I missing something? Maybe there's a simpler way without all the configuration hassle?
https://redd.it/1qagk8i
@r_php
Reddit
From the PHP community on Reddit
Explore this post and more from the PHP community
A slightly faster language server for php-cs-fixer
https://github.com/balthild/php-cs-fixer-lsp
It starts php-cs-fixer runners and keep them running in the background. This makes formatOnSave less laggy.
https://redd.it/1qb97qn
@r_php
https://github.com/balthild/php-cs-fixer-lsp
It starts php-cs-fixer runners and keep them running in the background. This makes formatOnSave less laggy.
https://redd.it/1qb97qn
@r_php
GitHub
GitHub - balthild/php-cs-fixer-lsp
Contribute to balthild/php-cs-fixer-lsp development by creating an account on GitHub.
How do you track temporary workarounds in Laravel projects?
In large Laravel applications, temporary workarounds often turn into permanent technical debt if they aren’t tracked carefully.
One approach is to **mark workarounds with a denoscription and an expiration date using PHP attributes**. With this system, teams can:
* List all workarounds and their current status (healthy or expired)
* Fail CI/CD builds when a workaround has expired
* Provide local feedback when expired code is executed (only in local environments)
Controller classes and methods can be automatically discovered, while other classes (services, jobs, listeners, etc.) can be explicitly enforced where needed.
This strategy helps teams enforce accountability and catch forgotten workarounds before they become problems.
For anyone interested, there’s an open-source implementation here: [https://github.com/medmahmoudhdaya/laravel-deadlock](https://github.com/medmahmoudhdaya/laravel-deadlock)
https://redd.it/1qauky3
@r_php
In large Laravel applications, temporary workarounds often turn into permanent technical debt if they aren’t tracked carefully.
One approach is to **mark workarounds with a denoscription and an expiration date using PHP attributes**. With this system, teams can:
* List all workarounds and their current status (healthy or expired)
* Fail CI/CD builds when a workaround has expired
* Provide local feedback when expired code is executed (only in local environments)
Controller classes and methods can be automatically discovered, while other classes (services, jobs, listeners, etc.) can be explicitly enforced where needed.
This strategy helps teams enforce accountability and catch forgotten workarounds before they become problems.
For anyone interested, there’s an open-source implementation here: [https://github.com/medmahmoudhdaya/laravel-deadlock](https://github.com/medmahmoudhdaya/laravel-deadlock)
https://redd.it/1qauky3
@r_php
GitHub
GitHub - medmahmoudhdaya/laravel-deadlock
Contribute to medmahmoudhdaya/laravel-deadlock development by creating an account on GitHub.
CKEditor 5 Symfony Integration
https://github.com/Mati365/ckeditor5-symfony
https://redd.it/1qanc82
@r_php
https://github.com/Mati365/ckeditor5-symfony
https://redd.it/1qanc82
@r_php
GitHub
GitHub - Mati365/ckeditor5-symfony: CKEditor 5 Integration for Symfony A modern, powerful rich text editor integration for Symfony…
CKEditor 5 Integration for Symfony A modern, powerful rich text editor integration for Symfony applications. Easily configure builds, manage file uploads, and use custom toolbar sets directly withi...
SymfonyLive Paris 2026: "100 crons par seconde, le Scheduler se venge"
https://symfony.com/blog/symfonylive-paris-2026-100-crons-par-seconde-le-scheduler-se-venge?utm_medium=feed&utm_source=Symfony%20Blog%20Feed
https://redd.it/1qbobfk
@r_php
https://symfony.com/blog/symfonylive-paris-2026-100-crons-par-seconde-le-scheduler-se-venge?utm_medium=feed&utm_source=Symfony%20Blog%20Feed
https://redd.it/1qbobfk
@r_php
Symfony
SymfonyLive Paris 2026: "100 crons par seconde, le Scheduler se venge" (Symfony Blog)
Quand un simple cron ne suffit plus. **De 1 tâche planifiée à 100 crons par seconde**, Jérémie Augustin partage un retour d’expérience concret sur la scalabilité, l’observabilité et les …
Weekly help thread
Hey there!
This subreddit isn't meant for help threads, though there's one exception to the rule: in this thread you can ask anything you want PHP related, someone will probably be able to help you out!
https://redd.it/1qao5uz
@r_php
Hey there!
This subreddit isn't meant for help threads, though there's one exception to the rule: in this thread you can ask anything you want PHP related, someone will probably be able to help you out!
https://redd.it/1qao5uz
@r_php
Reddit
From the PHP community on Reddit
Explore this post and more from the PHP community
Laravel performance benchmarks PHP 8.2 vs 8.3 vs 8.4 vs 8.5
https://sevalla.com/blog/laravel-benchmarks/
https://redd.it/1qbsvy5
@r_php
https://sevalla.com/blog/laravel-benchmarks/
https://redd.it/1qbsvy5
@r_php
Sevalla
Laravel performance benchmarks — PHP 8.2 vs 8.3 vs 8.4 vs 8.5
See how different PHP versions impact Laravel performance with our comprehensive benchmarks.
You can add arguments/options to any artisan CLI commands, even if they aren't yours
Our use case: Our permission system is very strict, and if no user is logged in (web) or tied to a job (queue) then permission checks are rejected.
But this interfers with tinker, which we use on the CLI (the web version is not affected, since we are logged in) and we didn't want to disable permissions for the whole CLI.
Solution: two simple listeners to add CLI arguments/options to any artisan commands:
<?php
namespace App\Listeners;
use Illuminate\Console\Events\ArtisanStarting;
use Symfony\Component\Console\Input\InputOption;
class AddPermissionsFlagsToConsoleCommand
{
public function handle(ArtisanStarting $event): void
{
$definition = $event->artisan->getDefinition();
$definition->addOption(new InputOption('--disable-permissions', null, InputOption::VALUE_NONE, 'Disable all permissions check'));
$event->artisan->setDefinition($definition);
}
}
<?php
namespace App\Listeners;
use App\Features\Permissions\Permissions;
use Exception;
use Illuminate\Console\Events\CommandStarting;
class ResolvePermissionsForConsoleCommand
{
const DISALLOWED_COMMANDS = [
'about',
];
const REQUIRED_COMMANDS = [
];
public function handle(CommandStarting $event): void
{
$disablePermissions = $event->input->getOption('disable-permissions');
if (! $disablePermissions) {
return;
}
if (\in_array($event->command, self::DISALLOWED_COMMANDS)) {
throw new Exception('You cannot specify --disable-permissions for this command');
}
if (\in_array($event->command, self::REQUIRED_COMMANDS)) {
throw new Exception('You must specify --disable-permissions to run this command');
}
// YOUR OWN LOGIC HERE
Permissions::bypassPermissions(true);
}
}
https://redd.it/1qbu7tp
@r_php
Our use case: Our permission system is very strict, and if no user is logged in (web) or tied to a job (queue) then permission checks are rejected.
But this interfers with tinker, which we use on the CLI (the web version is not affected, since we are logged in) and we didn't want to disable permissions for the whole CLI.
Solution: two simple listeners to add CLI arguments/options to any artisan commands:
<?php
namespace App\Listeners;
use Illuminate\Console\Events\ArtisanStarting;
use Symfony\Component\Console\Input\InputOption;
class AddPermissionsFlagsToConsoleCommand
{
public function handle(ArtisanStarting $event): void
{
$definition = $event->artisan->getDefinition();
$definition->addOption(new InputOption('--disable-permissions', null, InputOption::VALUE_NONE, 'Disable all permissions check'));
$event->artisan->setDefinition($definition);
}
}
<?php
namespace App\Listeners;
use App\Features\Permissions\Permissions;
use Exception;
use Illuminate\Console\Events\CommandStarting;
class ResolvePermissionsForConsoleCommand
{
const DISALLOWED_COMMANDS = [
'about',
];
const REQUIRED_COMMANDS = [
];
public function handle(CommandStarting $event): void
{
$disablePermissions = $event->input->getOption('disable-permissions');
if (! $disablePermissions) {
return;
}
if (\in_array($event->command, self::DISALLOWED_COMMANDS)) {
throw new Exception('You cannot specify --disable-permissions for this command');
}
if (\in_array($event->command, self::REQUIRED_COMMANDS)) {
throw new Exception('You must specify --disable-permissions to run this command');
}
// YOUR OWN LOGIC HERE
Permissions::bypassPermissions(true);
}
}
https://redd.it/1qbu7tp
@r_php
Reddit
From the laravel community on Reddit
Explore this post and more from the laravel community
Unit testing and TDD: useful or overrated? Contrasting opinions
I came across an old article that starts with: "Test-first fundamentalism is like abstinence-only sex ed: An unrealistic, ineffective morality campaign for self-loathing and shaming."
Searching online, I discovered that several prominent programmers (DHH, Casey Muratori, James Coplien) are very critical of the intensive TDD/unit testing approach. They argue that:
\- Mock tests give a false sense of security
\- Code becomes more complex just to be testable
\- Tests constantly break during refactoring
\- They don't replace end-to-end system tests
On the other hand, the Laravel/Symfony ecosystem (and many companies) strongly promotes this approach.
I have to say that after many years, I'm also starting to think that writing tests is more of a bureaucratic duty than a real help to programming. What do you think?
https://redd.it/1qc49z1
@r_php
I came across an old article that starts with: "Test-first fundamentalism is like abstinence-only sex ed: An unrealistic, ineffective morality campaign for self-loathing and shaming."
Searching online, I discovered that several prominent programmers (DHH, Casey Muratori, James Coplien) are very critical of the intensive TDD/unit testing approach. They argue that:
\- Mock tests give a false sense of security
\- Code becomes more complex just to be testable
\- Tests constantly break during refactoring
\- They don't replace end-to-end system tests
On the other hand, the Laravel/Symfony ecosystem (and many companies) strongly promotes this approach.
I have to say that after many years, I'm also starting to think that writing tests is more of a bureaucratic duty than a real help to programming. What do you think?
https://redd.it/1qc49z1
@r_php
Reddit
From the PHP community on Reddit
Explore this post and more from the PHP community
Why I built another Audit Bundle for Symfony
# Why I built another Audit Bundle for Symfony (and why you might need it)
When I started my latest Symfony project, I looked at the existing options for entity auditing. While there are some massive, well-established bundles out there, I ran into a few common headaches:
They felt "heavy": Often bringing in dependencies or UI components I didn't need.
Hard to customize: Trying to exclude specific fields or logic was surprisingly difficult.
No Integrity Checks: I had no easy way to verify if someone had manually tampered with the audit logs in the database.
So, I built AuditTrailBundle. Here is why it’s different:
1. Conditional Logging (The "Smart" Audit) Sometimes you don’t want to log everything. Logging a last_login update every 5 minutes is a waste of storage. I added Expression Language support, allowing you to set rules so the bundle only logs changes if a specific condition is met or if a high-priority field actually changed.
2. If audit logs are used for compliance, you must be able to detect whether someone has manually altered them to hide their tracks. This bundle includes an integrity check feature that verifies the audit history remains untouched and authentic.
3. Performance-First Architecture Many bundles slow down the main request because of how they handle entity relations. This bundle hooks into the onFlush event, ensuring the audit trail is part of the same database transaction. If your data rolls back, the audit rolls back. No orphaned logs, no performance lag.
4. The "Split Transport" Advantage One of the biggest fears with auditing is bloating the primary database. If your app has millions of transactions, your audit_log table can become a maintenance nightmare. I built a Split Transport feature so you aren't forced to save logs in the same place as your app data. You can route audit trails to a different database connection or an external transport, allowing you to scale without slowing down your high-traffic tables.
5. "Silent Collection" Tracking Most lightweight bundles only track simple fields like strings or integers. When it comes to Many-to-Many or One-to-Many relations, they often fail to log exactly what happened—they just say the collection "changed." My bundle performs a Collection Diff, identifying precisely which IDs were added or removed from a collection.
I didn't build this bundle to replace the giants of the Symfony ecosystem, but to provide a modern, high-performance alternative for developers who need precision and integrity.
By focusing on conditional logging, split transports for scalability, and collection tracking, AuditTrailBundle gives you a "paper trail" that is both lightweight and enterprise-ready.
Check out the project on GitHub: https://github.com/rcsofttech85/AuditTrailBundle
I’m actively looking for feedback!
https://redd.it/1qcb9lr
@r_php
# Why I built another Audit Bundle for Symfony (and why you might need it)
When I started my latest Symfony project, I looked at the existing options for entity auditing. While there are some massive, well-established bundles out there, I ran into a few common headaches:
They felt "heavy": Often bringing in dependencies or UI components I didn't need.
Hard to customize: Trying to exclude specific fields or logic was surprisingly difficult.
No Integrity Checks: I had no easy way to verify if someone had manually tampered with the audit logs in the database.
So, I built AuditTrailBundle. Here is why it’s different:
1. Conditional Logging (The "Smart" Audit) Sometimes you don’t want to log everything. Logging a last_login update every 5 minutes is a waste of storage. I added Expression Language support, allowing you to set rules so the bundle only logs changes if a specific condition is met or if a high-priority field actually changed.
2. If audit logs are used for compliance, you must be able to detect whether someone has manually altered them to hide their tracks. This bundle includes an integrity check feature that verifies the audit history remains untouched and authentic.
3. Performance-First Architecture Many bundles slow down the main request because of how they handle entity relations. This bundle hooks into the onFlush event, ensuring the audit trail is part of the same database transaction. If your data rolls back, the audit rolls back. No orphaned logs, no performance lag.
4. The "Split Transport" Advantage One of the biggest fears with auditing is bloating the primary database. If your app has millions of transactions, your audit_log table can become a maintenance nightmare. I built a Split Transport feature so you aren't forced to save logs in the same place as your app data. You can route audit trails to a different database connection or an external transport, allowing you to scale without slowing down your high-traffic tables.
5. "Silent Collection" Tracking Most lightweight bundles only track simple fields like strings or integers. When it comes to Many-to-Many or One-to-Many relations, they often fail to log exactly what happened—they just say the collection "changed." My bundle performs a Collection Diff, identifying precisely which IDs were added or removed from a collection.
I didn't build this bundle to replace the giants of the Symfony ecosystem, but to provide a modern, high-performance alternative for developers who need precision and integrity.
By focusing on conditional logging, split transports for scalability, and collection tracking, AuditTrailBundle gives you a "paper trail" that is both lightweight and enterprise-ready.
Check out the project on GitHub: https://github.com/rcsofttech85/AuditTrailBundle
I’m actively looking for feedback!
https://redd.it/1qcb9lr
@r_php
GitHub
GitHub - rcsofttech85/AuditTrailBundle: A Symfony audit bundle for Doctrine ORM. Lightweight entity tracking and audit logging…
A Symfony audit bundle for Doctrine ORM. Lightweight entity tracking and audit logging for compliance. - rcsofttech85/AuditTrailBundle
Does LAMP still have a future?
I'm a beginner to web development completely self-taught, and I want to know if learning the LAMP stack and not relying on heavy frameworks is worth my time. I'm primarily self motivated to build fun things for myself/friends, and getting a job in this field is secondary. I hear a lot of bad things about PHP, but recently I built a drawing program powered by Slim and MariaDB using this noscript I found github.com/desuwa/tegaki (I am not the maintainer, I just wanted to share it). The app is simple and I use twig to render pages: a user can post a drawing, browse a gallery of all drawings, and replay a drawing.
I really enjoyed writing in PHP, the syntax was weird but it had everything built in like the PDO for my database. I'm just worried that when I want to implement more complicated features like auth through Twitter/Discord or authz with RBAC doing it all by hand is kind a waste when Django has it built in and I can use Better Auth with NodeJS. I know about Laravel/Symfony but they honestly don't interest me at all. Also what if I want to use S3 to store files or run background workers, all my research points to just sticking with NodeJS runtime or Python. Can any experienced dev give advice?
https://redd.it/1qcbfgi
@r_php
I'm a beginner to web development completely self-taught, and I want to know if learning the LAMP stack and not relying on heavy frameworks is worth my time. I'm primarily self motivated to build fun things for myself/friends, and getting a job in this field is secondary. I hear a lot of bad things about PHP, but recently I built a drawing program powered by Slim and MariaDB using this noscript I found github.com/desuwa/tegaki (I am not the maintainer, I just wanted to share it). The app is simple and I use twig to render pages: a user can post a drawing, browse a gallery of all drawings, and replay a drawing.
I really enjoyed writing in PHP, the syntax was weird but it had everything built in like the PDO for my database. I'm just worried that when I want to implement more complicated features like auth through Twitter/Discord or authz with RBAC doing it all by hand is kind a waste when Django has it built in and I can use Better Auth with NodeJS. I know about Laravel/Symfony but they honestly don't interest me at all. Also what if I want to use S3 to store files or run background workers, all my research points to just sticking with NodeJS runtime or Python. Can any experienced dev give advice?
https://redd.it/1qcbfgi
@r_php
GitHub
GitHub - desuwa/tegaki: Oekaki-style painter app in JavaScript
Oekaki-style painter app in JavaScript. Contribute to desuwa/tegaki development by creating an account on GitHub.
Ran some benchmarks against go, thought you guys might find this interesting (not here to hate)
so full disclosure i primarily write php for work, laravel specifically. pays the bills, i like it
but i was curious about the actual performance difference vs go since everyone has opinions but nobody posts real numbers. built the same api in both, laravel 11 with php 8.2 and go fiber. same mysql db with 500k records, same endpoints, same queries. tried to keep everything fair
screenshots attached. yeah go is faster, obviously. thats not surprising, its compiled. but i was kinda shocked by how much faster on the heavy endpoint - we're talking 30 seconds vs 1.5 seconds for basically the same sql
few things i learned:
- most of laravels overhead is just... being laravel? the actual eloquent queries arent that slow
- for basic crud the difference probably doesnt matter in real apps
- for cpu heavy stuff like aggregating data across multiple tables... ok yeah go absolutely destroys it
honestly still gonna use laravel for most things because i can ship features way faster. but for the few endpoints that need to be actually fast? might be worth writing those in go
anyone else running a mixed stack? curious how people handle this in production
https://redd.it/1qcf71g
@r_php
so full disclosure i primarily write php for work, laravel specifically. pays the bills, i like it
but i was curious about the actual performance difference vs go since everyone has opinions but nobody posts real numbers. built the same api in both, laravel 11 with php 8.2 and go fiber. same mysql db with 500k records, same endpoints, same queries. tried to keep everything fair
screenshots attached. yeah go is faster, obviously. thats not surprising, its compiled. but i was kinda shocked by how much faster on the heavy endpoint - we're talking 30 seconds vs 1.5 seconds for basically the same sql
few things i learned:
- most of laravels overhead is just... being laravel? the actual eloquent queries arent that slow
- for basic crud the difference probably doesnt matter in real apps
- for cpu heavy stuff like aggregating data across multiple tables... ok yeah go absolutely destroys it
honestly still gonna use laravel for most things because i can ship features way faster. but for the few endpoints that need to be actually fast? might be worth writing those in go
anyone else running a mixed stack? curious how people handle this in production
https://redd.it/1qcf71g
@r_php
Reddit
From the PHP community on Reddit
Explore this post and more from the PHP community
Sitemap Generator in Laravel.
Hello guys. I have code like that:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Services\Sitemap\SitemapService;
class GenerateSitemap extends Command
{
protected
$signature
= 'sitemap:generate';
protected
$denoscription
= 'Generate sitemap.xml including news';
public function handle(SitemapService
$service
)
{
$path
= public_path('sitemap.xml');
$service
->generate(
$path
);
$this
->info("Sitemap generated: {
$path
}");
}
}
<?php
declare(strict_types=1);
namespace App\Services\Sitemap;
use Carbon\Carbon;
use SimpleXMLElement;
use Illuminate\Support\Facades\File;
class SitemapService
{
private const BASE_URL = 'https://example.com';
public function generate(string
$outputPath
): void
{
$xml
= new SimpleXMLElement(
'<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>'
);
$staticUrls
= [
['/', 'daily', '1.0'],
['/section-a', 'daily', '0.9'],
['/section-b', 'hourly', '0.9'],
['/section-c', 'weekly', '0.8'],
['/section-d', 'daily', '0.8'],
['/about', 'monthly', '0.5'],
['/contact', 'monthly', '0.5'],
];
foreach (
$staticUrls
as [
$path
,
$freq
,
$priority
]) {
$this
->addUrl(
$xml
,
self::BASE_URL .
$path
,
now(),
$freq
,
$priority
);
}
Model::where('status', 1)
->whereNotNull('published_at')
->latest('published_at')
->chunk(500, function (
$items
) use (
$xml
) {
foreach (
$items
as
$item
) {
$this
->addUrl(
$xml
,
self::BASE_URL . '/content/' .
$item
->
slug
,
$item
->
published_at
,
'daily',
'0.8'
);
}
});
File::put(
$outputPath
,
$xml
->asXML());
}
private function addUrl(
SimpleXMLElement
$xml
,
string
$loc
,
mixed
$lastmod
,
string
$freq
,
string
$priority
): void {
$url
=
$xml
->addChild('url');
$url
->addChild('loc', htmlspecialchars(
$loc
, ENT_XML1));
$url
->addChild('lastmod', Carbon::parse(
$lastmod
)->toDateString());
$url
->addChild('changefreq',
$freq
);
$url
->addChild('priority',
$priority
);
}
}
Schedule::command('sitemap:generate')
->hourly()
->name('hourly-sitemap-refresh');
It generate sitemap.xml automatically. And update it in one hour right? Now is there is a way that ping it to search engines automatically? and how can I check it works correctly?
https://redd.it/1qch9lu
@r_php
Hello guys. I have code like that:
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Services\Sitemap\SitemapService;
class GenerateSitemap extends Command
{
protected
$signature
= 'sitemap:generate';
protected
$denoscription
= 'Generate sitemap.xml including news';
public function handle(SitemapService
$service
)
{
$path
= public_path('sitemap.xml');
$service
->generate(
$path
);
$this
->info("Sitemap generated: {
$path
}");
}
}
<?php
declare(strict_types=1);
namespace App\Services\Sitemap;
use Carbon\Carbon;
use SimpleXMLElement;
use Illuminate\Support\Facades\File;
class SitemapService
{
private const BASE_URL = 'https://example.com';
public function generate(string
$outputPath
): void
{
$xml
= new SimpleXMLElement(
'<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></urlset>'
);
$staticUrls
= [
['/', 'daily', '1.0'],
['/section-a', 'daily', '0.9'],
['/section-b', 'hourly', '0.9'],
['/section-c', 'weekly', '0.8'],
['/section-d', 'daily', '0.8'],
['/about', 'monthly', '0.5'],
['/contact', 'monthly', '0.5'],
];
foreach (
$staticUrls
as [
$path
,
$freq
,
$priority
]) {
$this
->addUrl(
$xml
,
self::BASE_URL .
$path
,
now(),
$freq
,
$priority
);
}
Model::where('status', 1)
->whereNotNull('published_at')
->latest('published_at')
->chunk(500, function (
$items
) use (
$xml
) {
foreach (
$items
as
$item
) {
$this
->addUrl(
$xml
,
self::BASE_URL . '/content/' .
$item
->
slug
,
$item
->
published_at
,
'daily',
'0.8'
);
}
});
File::put(
$outputPath
,
$xml
->asXML());
}
private function addUrl(
SimpleXMLElement
$xml
,
string
$loc
,
mixed
$lastmod
,
string
$freq
,
string
$priority
): void {
$url
=
$xml
->addChild('url');
$url
->addChild('loc', htmlspecialchars(
$loc
, ENT_XML1));
$url
->addChild('lastmod', Carbon::parse(
$lastmod
)->toDateString());
$url
->addChild('changefreq',
$freq
);
$url
->addChild('priority',
$priority
);
}
}
Schedule::command('sitemap:generate')
->hourly()
->name('hourly-sitemap-refresh');
It generate sitemap.xml automatically. And update it in one hour right? Now is there is a way that ping it to search engines automatically? and how can I check it works correctly?
https://redd.it/1qch9lu
@r_php
Reddit
From the PHP community on Reddit
Explore this post and more from the PHP community
Introducing the Symfony 8 Certification
https://symfony.com/blog/introducing-the-symfony-8-certification?utm_medium=feed&utm_source=Symfony%20Blog%20Feed
https://redd.it/1qcka5b
@r_php
https://symfony.com/blog/introducing-the-symfony-8-certification?utm_medium=feed&utm_source=Symfony%20Blog%20Feed
https://redd.it/1qcka5b
@r_php
Symfony
Introducing the Symfony 8 Certification (Symfony Blog)
The certification exam for the new Symfony 8 version is now available. Purchase your voucher today to become one of the first Symfony 8 certified developers.