I have two tables 'User' and 'Address', there is OneToOne relation between them as User table has a column 'address_id' which stores 'id' of Address table.
Here is the annotation in User Entity:
/**
* @ORM\OneToOne(targetEntity="App\Entity\address", cascade={"persist", "remove"})
* @ORM\JoinColumn(nullable=false)
*/
private $address;
Security.yaml:
security:
encoders:
App\Entity\User:
algorithm: bcrypt
providers:
my_provider:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
form_login:
login_path: login
check_path: login
provider: my_provider
default_target_path: dashboard
logout:
path: /logout
target: /
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/dashboard, roles: ROLE_USER }
Controller:
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
/**
* @Route("/login", name="login")
*/
public function login(Request $request,AuthenticationUtils $utils)
{
// get the login error if there is one
$error = $utils->getLastAuthenticationError();
// dump($error);die;
// last username entered by the user
$lastUsername = $utils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
public function logout()
{
# code...
}
}
I get this error when I insert my username and password:
Authentication request could not be processed due to a system problem.
This is what I get when I dump() the error in controller.
SecurityController.php on line 20: AuthenticationServiceException {#189 ▼ -token: UsernamePasswordToken {#236 ▶} #message: "The target-entity App\Entity\address cannot be found in 'App\Entity\User#address'." #code: 0 #file: "/home/users/kumar.saurabh/www/html/symfony/test-project/vendor/symfony/security-core/Authentication/Provider/DaoAuthenticationProvider.php" #line: 85 trace: {▶} }
When I remove $address variables and its getter and setter function then the login is working fine, but when I am using this it gives me above mentioned error.
How can I can achieve this by using Foreign key?
I'm using Symfony 4.2.
Beware the case, replace App\Entity\address by App\Entity\Address, update your schema and it should be fine
/**
* @ORM\OneToOne(targetEntity="App\Entity\address", cascade={"persist", "remove"})
* @ORM\JoinColumn(nullable=false)
*/
private $address;
should be
/**
* @ORM\OneToOne(targetEntity="App\Entity\Address", cascade={"persist", "remove"})
* @ORM\JoinColumn(nullable=false)
*/
private $address;