I'm trying to create a product that the current authenticated user created.
The user has a relationship with the product entity, i need to make a way for a user to create product with the user associated with it.
I'm following this tutorial, but it doesn't cover how to store a product with a current user
This is what i have so far
ProductController.php
public function create(Request $request)
{
$category = new Category();
$category->setName($request->get('category'));
$user = new User();
// how would i get the current user and set it to a product.
$entityManager = $this->getDoctrine()->getManager();
$product = new Product();
$product->setName($request->get('title'));
$product->setPrice($request->get('price'));
$product->setDescription($request->get('description'));
$product->setCategory($category);
$entityManager->persist($category);
$entityManager->persist($product);
$entityManager->flush();
return $this->redirectToRoute('products');
}
Should i use this method or try something else ?
Entity\User.php
public function addProduct(Product $product): self
{
if (!$this->products->contains($product)) {
$this->products[] = $product;
$product->setUser($this);
}
return $this;
}
Entity\Product.php
<?php
namespace App\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity(repositoryClass="App\Repository\ProductRepository")
*/
class Product
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=190)
*/
private $name;
/**
* @ORM\Column(type="integer")
*/
private $price;
/**
* @ORM\Column(type="text")
*/
private $description;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Category", inversedBy="products")
* @ORM\JoinColumn(nullable=false)
*/
private $category;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="products")
* @ORM\JoinColumn(nullable=false)
*/
private $user;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
public function getPrice(): ?int
{
return $this->price;
}
public function setPrice(int $price): self
{
$this->price = $price;
return $this;
}
public function getDescription(): ?string
{
return $this->description;
}
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
public function getCategory(): ?Category
{
return $this->category;
}
public function setCategory(?Category $category): self
{
$this->category = $category;
return $this;
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
}