Installation:
composer require friendsofsymfony/user-bundle
Ensure Symfony\Bundle\FrameworkBundle\FrameworkBundle and Symfony\Bundle\SecurityBundle\SecurityBundle are installed.
Enable the Bundle:
Add to config/bundles.php:
return [
// ...
FriendsOfSymfony\UserBundle\FOSUserBundle::class => ['all' => true],
];
Configure Database & Security:
Update config/packages/security.yaml to integrate FOSUserBundle’s provider:
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
Configure fos_user in config/packages/fos_user.yaml:
fos_user:
db_driver: orm # or 'mongodb', 'couchdb'
firewall_name: main
user_class: App\Entity\User
Create User Entity:
Extend FOS\UserBundle\Model\User:
// src/Entity/User.php
namespace App\Entity;
use FOS\UserBundle\Model\User as BaseUser;
class User extends BaseUser {}
Run Migrations:
php bin/console doctrine:schema:update --force
First Use Case: Register a user via the built-in controller (or create a custom form):
php bin/console fos:user:create
User Registration:
FOS\UserBundle\Form\Type\RegistrationFormType.registration.html.twig) or use the controller (FOS\UserBundle\Controller\RegistrationController).// src/Form/RegistrationFormType.php
use FOS\UserBundle\Form\Type\RegistrationFormType as BaseType;
class RegistrationFormType extends BaseType {
public function buildForm(FormBuilderInterface $builder, array $options) {
parent::buildForm($builder, $options);
$builder->add('custom_field', TextType::class);
}
}
Password Reset:
fos:user:resetting:send-email command or the /resetting/request route.fos_user.yaml:
resetting:
token_ttl: 86400 # 1 day
Authentication Integration:
fos_user.user_provider.username_email in security.yaml:
firewalls:
main:
form_login:
provider: fos_userbundle
Profile Management:
FOS\UserBundle\Form\Type\ProfileFormType) or override the controller.$builder->add('avatar', FileType::class, ['label' => 'Profile Picture']);
Event Listeners:
fos_user.registered):
// src/EventListener/UserListener.php
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class UserListener implements EventSubscriberInterface {
public static function getSubscribedEvents() {
return [
FOSUserEvents::REGISTERED => 'onUserRegistered',
];
}
public function onUserRegistered(FilterUserResponseEvent $event) {
// Send welcome email, etc.
}
}
Laravel-Specific Adaptations:
spatie/laravel-fosuserbundle (a Laravel wrapper) for seamless integration with Laravel’s ecosystem:
composer require spatie/laravel-fosuserbundle
config/fos_user.php (Laravel’s style):
'db_driver' => 'eloquent',
'user_model' => App\Models\User::class,
Custom User Model:
Authenticatable alongside FOS\UserBundle\Model\User:
use Illuminate\Foundation\Auth\User as Authenticatable;
use FOS\UserBundle\Model\User as BaseUser;
class User extends Authenticatable implements BaseUser {
use FOS\UserBundle\Model\UserTrait;
}
Blade Templates:
return view('auth.register', ['form' => $form->createView()]);
Route Customization:
routes/web.php:
Route::get('/register', 'FOS\UserBundle\Controller\RegistrationController@register')->name('fos_user_registration_register');
Validation Rules:
$builder->add('email', EmailType::class, [
'constraints' => [
new NotBlank(),
new Email(),
new Callback([$this, 'checkEmailUnique']),
],
]);
Deprecated Symfony Components:
Doctrine vs. Eloquent:
spatie/laravel-fosuserbundle or manually adapt the User entity to work with Eloquent’s query builder.Token Generation:
FOS\UserBundle\Util\TokenGenerator. Override this class if you need custom token logic (e.g., UUIDs instead of hashes).Form Type Conflicts:
password field). Use unique names:
$builder->add('plainPassword', RepeatedType::class, [
'type' => PasswordType::class,
'first_name' => 'password',
'second_name' => 'confirm_password',
]);
Email Configuration:
Swiftmailer. In Laravel, configure swiftmailer in .env or config/mail.php:
MAIL_DRIVER=smtp
MAIL_HOST=mail.example.com
CSRF Protection:
{{ form_start(form, {'attr': {'novalidate': 'novalidate'}}) }}
{{ form_row(form._token) }} {# CSRF token #}
Event Debugging:
public function onUserRegistered(FilterUserResponseEvent $event) {
dump($event->getUser());
dump($event->getResponse());
}
Database Migrations:
User entity’s table name (@ORM\Table(name="fos_user")). Override in Laravel:
class User extends Authenticatable {
protected $table = 'users';
}
Form Errors:
$form->handleRequest($request);
if (!$form->isValid()) {
dd($form->getErrors(true)); // Debug errors
}
Token Expiry:
fos_user.yaml:
resetting:
token_ttl: 10 # 10 seconds for testing
Custom User Fields:
User entity and update the form type:
// src/Entity/User.php
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $phoneNumber;
Role Management:
getRoles() or adding a Role entity:
public function getRoles() {
$roles = $this->roles;
$roles[] = 'ROLE_CUSTOM';
return array_unique($roles);
}
Profile Picture Handling:
composer require vich/uploader-bundle
Configure in fos_user.yaml:
service:
user_class: App\Entity\User
user_manager: fos_user.user_manager.default
API Integration:
How can I help you explore Laravel packages today?