How can I get the current Post? I'm trying to redirect to my current post where im sending my vote but this method that i created redirects to Oldest Post created by this user.
public function ScoreAction(Request $request){
$em = $this->getDoctrine()->getManager();
$idPoster = $request->request->get('id_posterUser');
$positive= $request->request->get('positive');
$negative= $request->request->get('negative');
$user= $em->getRepository(User::class)->findOneById($idPoster);
$topic = $em->getRepository(Topic::class)->findOneByUser($user->getId());
$score = $usuari->getReputation();
if ($positive!= null) {
$score = $score + 1;
}
if($negative!= null){
$score = $score - 1;
}
$user->setReputation($score );
$em->persist($user);
$em->flush();
$redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));
return $this->redirect($redirect);
}
Edit: Added my Solution.
Solution :
public function ScoreAction(Request $request){
$em = $this->getDoctrine()->getManager();
$idTopic = $request->request->get('id_topic');
$idPoster = $request->request->get('id_poster');
$positive= $request->request->get('positive');
$negative= $request->request->get('negatiu');
$user= $em->getRepository(User::class)->findOneById($idPoster);
$topic = $em->getRepository(Topic::class)->findOneById($idTopic);
$score= $user->getReputation();
if ($positive!= null) {
$score= $score+ 1;
}
if($negative!= null){
$score= $score- 1;
}
$user->setReputation($score);
$em->persist($user);
$em->flush();
$redirect = $this->generateUrl('discutea_forum_post', array('slug' => $topic->getSlug()));
return $this->redirect($redirect);
}
You are searching topic by user:
$topic = $em->getRepository(Topic::class)->findOneByUser($user->getId());
findOneByUser - builds query WHERE user.id = :user_id LIMIT 1
For get the last Topic you need to add ordering.
$topic = $em->getRepository(Topic::class)->findOneBy(
array('user' => $user),
array('id' => 'desc')
);
Related
i'm working with laravel project, and i have an issue that is update query result return false value if i update with the same data, how to solve this? do i have to validate first before run the query and send a notification that the data is the same?
well this is my codes
public function update(Request $request)
{
$kamar_id = $request->input('kamar_id');
$title = $request->input('title');
$content = $request->input('content');
$keyword = $request->input('keyword');
$description = $request->input('description');
$prolog = $request->input('prolog');
$path = $request->input('path');
$sort = $request->input('sort');
$status = $request->input('status');
$type = $request->input('type');
$user_id = $request->input('user_id');
if (empty($request->input('path'))) {
$path = serialize(array('data/def.png'));
}else{
$path = serialize(explode(',', $request->input('path')));
}
$data = array('title' => $title,
'content' => $content,
'keyword' => $keyword,
'description' => $description,
'prolog' => $prolog,
'path' => $path,
'sort' => $sort,
'status' => $status,
'type' => $type,
'user_id' => $user_id);
// echo($kamar_id);
$update = Kamar::where('kamar_id',$kamar_id)->update($data);
if ($update) {
$response['status'] = 1;
}else{
$response['status'] = 0;
}
return response()->json($response);
}
thanks for helping me
Laravel Eloquent Update method returns true if anything updated in database from your query and return false if nothing is updated in database from your query.
refer:
https://laravel.com/docs/5.8/eloquent#updates
!nullTry
$update = Kamar::where('kamar_id','=',$kamar_id)->first();
if (!null($update))
{
$update->title = $title;
$update->content = $content;
$update->keyword = $keyword;
$update->description = $description;
$update->prolog = $prolog;
$update->path = $path;
$update->sort = $sort;
$update->status = $status;
$update->type = $type;
$update->user_id = $user_id;
$update->save();
$response['status'] = 1;
}
else
{
$response['status'] = 0;
}
Try using this
$kamarObj = new Kamar();
$kamarData = $kamarObj->find($kamar_id);
$result = $kamarData->update($data);
You can force updated_at column to be updated (or you can create this column if you don't have). So the query will be always updated.
I'm trying to create a function that will replicate/clone/duplicate a product including all it's properties and it's shipping options.
However, I succeeded to duplicate the product but the shipping options are not replicated. See my codes below;
Any help will be highly appreciated
Thanks
public function CreateProductPost(Request $request){
if (Auth::user()->vendor == false) {
return redirect()->route('profile');
}
if ($request->name == null) {
session()->flash('errormessage','Product name is required');
return redirect()->back()->withInput();
}
if (mb_strlen($request->name) > 60) {
session()->flash('errormessage','Product name cannot be longer than 60 characters.');
return redirect()->back()->withInput();
}
if ($request->category_id == null) {
session()->flash('errormessage','Product category is required');
$shippingoptions[] = $opt;
}
}
$product = new Product;
$product->name = $request->name;
$product->uniqueid = random_int(10000, 99999);
$product->category_id = $category->id;
$product->description = $request->description;
$product->refund_policy = $request->refund_policy;
$product->fromc = $request->fromc;
$product->tocount = $request->tocount;
$product->price = $request->price;
$product->currency = $request->currency;
$product->inventory = $request->inventory;
if ($request->image !== null) {
$product->image = $request->image->store('uploads','public');
}
$product->buyout = 0;
$product->fe = $fe;
$product->seller_id = Auth::user()->id;
$product->save();
foreach ($shippingoptions as $opt) {
$so = new ShippingOption();
$so->product_id = $product->id;
$so->desc = $opt['desc'];
$so->days = $opt['days'];
$so->price = $opt['price'];
$so->save();
}
session()->flash('successmessage','Product successfully created');
return redirect()->route('products');
}
function DuplicateProductPost($uniqueid, Request $request){
$product = Product::where('uniqueid',$uniqueid)->first();
if ($product == null) {
return redirect()->route('products');
}
if (Auth::user()->id !== $product->seller->id) {
return redirect()->route('products');
}
$newProduct = $product->replicate();
$newProduct->uniqueid = random_int(10000, 99999);
$newProduct->save();
session()->flash('successmessage','Product successfully duplicated');
return redirect()->route('products');
}
Any help will be highly appreciated
Thanks
You need to replicate both your Product and ShippingOption models, so use the following logic:
$product = Product::where('uniqueid',$uniqueid)->first();
...
$newProduct = $product->replicate();
$newProduct->uniqueid = random_int(10000, 99999);
$newProduct->save();
foreach($product->shippingOptions AS $shippingOption){
$newShippingOption = $shippingOption->replicate();
$newShippingOption->product_id = $newProduct->id;
$newShippingOption->save();
}
Note, you need to have a relationship between Product and ShippingOption, otherwise you will need to manually query for them:
$oldShippingOptions = ShippingOption::where("product_id", "=", $product->id)->get();
foreach($oldShippingOptions AS $shippingOption){
...
}
The ->replicate() method does not clone all related records, as that might not be the intended requirement, so you need to do it manually.
I had a Laravel script installed, Now When the user fills in the new order form and makes an order for ordering, will be displayed:
"Trying to get property 'price' of non-object"
The error is for usercontroller and this line:
" $price = ($request->quantity * $servicePrice->price) / 1000;"
This part code is for new order in usercontroller:
public function newOrder()
{
$categories = Category::where('status', 1)->orderBy('name')->get();
return view('user.newOrder', compact('categories'));
}
public function getPack(Request $request)
{
$items = Service::where('category_id', $request->id)->where('status', 1)->orderBy('name')->get();
return $items;
}
public function getPackDetails(Request $request)
{
$items = Service::findOrFail($request->id);
return $items;
}
public function storeNewOrder(Request $request)
{
$this->validate($request, [
'category' => 'required',
'service' => 'required',
'link' => 'required',
'quantity' => 'required',
]);
$service = Service::where('category_id', $request->category)->where('id', $request->service)->first();
$servicePrice = ServicePrice::where('category_id', $request->category)->where('service_id', $request->service)->where('user_id', Auth::id())->first();
$item = new Order();
$user = User::findOrFail(Auth::id());
$transaction = new Transaction();
if ($request->quantity >= $service->min && $request->quantity <= $service->max) {
$price = ($request->quantity * $servicePrice->price) / 1000;
if ($user->balance >= $price) {
$item->category_id = $request->category;
$item->service_id = $request->service;
$item->user_id = Auth::id();
$item->service_no = $service->service_id;
$item->order_no = 0;
$item->link = $request->link;
$item->quantity = $request->quantity;
$item->price = $price;
$item->status = 'Pending';
$item->start_counter = 0;
$item->remains = $request->quantity;
$item->order_through = 'Web';
$item->save();
$user->balance = $user->balance - $price;
$user->save();
$transaction->user_id = Auth::id();
$transaction->amount = $price;
$transaction->user_balance = $user->balance;
$transaction->type = 1;
$transaction->trx = str_random(12);
$transaction->save();
send_email($user->email, $user->name, 'Order Placed Successfully', 'Your ' . $request->quantity . ' ' . $service->name . ' has been placed successfully.');
session()->flash('success', 'Order request send successfully');
return back();
} else {
session()->flash('alert', 'Insufficient Balance');
return back();
}
} else {
session()->flash('alert', 'Quantity should be within ' .
$service->min . ' to ' . $service->max);
return back();
}
}
Most probably the problem comes from this line:
$servicePrice = ServicePrice::where('category_id', $request->category)->where('service_id', $request->service)->where('user_id', Auth::id())->first();
If a query does not return any result from the database, the code will return null.
A good practice is to check if the result is null and you should handle it.
That means, before you use the $servicePrice, you need to check if it contains anything:
if(!$servicePrice){ //same result: if($servicePrice == null) {
//`$servicePrice==null`, so you should handle the error here - throw an exception or return
}
//your code here
$servicePrice = ServicePrice::where('category_id', $request->category)->where('service_id', $request->service)->where('user_id', Auth::id())->first();
Also, the authenticated user can be retrieved directly from:
$user = Auth::user();
If the visitor is not authenticated, $user will be null, for the same reason than the previous.
if(!$user){
//the user is NOT authenticated
} else {
//the user is authenticated
}
I have {{ knp_pagination_render(pagination1) }} on view InfCustumersBundle:Faktura:indexoryginal.html.twig
This code show me paginarion:
public function indexoryginalAction(Request $request) {
$em = $this->getDoctrine()->getManager();
$req = $em->getRepository('...:Faktura');
$qb = $req->createQueryBuilder('p');
$search = $qb
.
.
->getQuery();
$form = $this->createFormBuilder()
.
.
->getForm();
$paginator = $this->get('knp_paginator');
$pagination1 = $paginator->paginate(
$search, $request->query->get('page', 1)/* page number */, 5/* limit per page */
);
return $this->render('InfCustumersBundle:Faktura:indexoryginal.html.twig', array(
'pagination1' => $pagination1,
'form' => $form->createView()
));
and this work fine, but code bellow don't show pagination tags. Only the first 3 items. Where I made a mistake ?
public function indexAction(Request $request, $type = 1) {
$data = array();
$form = $this->createFormBuilder()
.
.
->getForm();
if ($request->isMethod('GET')) {
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$name = ($data['for'] == 'name' ? true : false);
if ($name) {
return $this->Name($form);
}
}
return $this->redirect($this->generateUrl('faktura_oryginal', array(
$this->get('session')->getFlashBag()->add('error', 'error')
)));
}
protected function Name($form) {
$em2 = $this->getDoctrine()->getManager();
$req = $em2->getRepository('InfCustomersBundle:Faktura');
$qb = $req->createQueryBuilder('p');
$query2 = $qb
.
.
->getQuery();
$entities2 = $query2->getResult();
if ($entities2) {
$paginator = $this->get('knp_paginator');
$request = $this->get('request_stack');
// $request = $this->getRequest();
$pagination1 = $paginator->paginate(
$query2, $request->getCurrentRequest()->query->get('page', 1)/* page number */, 3/* limit per page */
);
return $this->render('InfCustumersBundle:Faktura:indexoryginal.html.twig', array(
'pagination1' => $pagination1,
'form' => $form->createView()
));
} else {
return $this->redirect($this->generateUrl('faktura_oryginal', array( $this->get('session')->getFlashBag()->add('error', 'error')
)));
}
}
}
I found a solution
I changed:
$entities2 = $query2->getResult();
if ($entities2) {
to
$pagination1 = $paginator->paginate(
$query2, $request->getCurrentRequest()->query->get('page',1),25);
if (count($pagination1) > 0) {
and now is working well
I have created a form for an entity Event with user's fields like "email" and "password" what I use to create a user manually in the controller.
I can create the event and the user without problems, but I need to send a confirmation mail to enable the user. I can do it from the normal registration form, but here I don't know how to do it.
Sorry if my english isn't very good. I'm learning it.
The controller:
class EventController extends Controller
{
public function ajaxAction(Request $request) {
if (! $request->isXmlHttpRequest()) {
throw new NotFoundHttpException();
}
// Get the province ID
$id = $request->query->get('category_id');
$result = array();
// Return a list of cities, based on the selected province
$repo = $this->getDoctrine()->getManager()->getRepository('CASEventBundle:Subcategory');
$subcategories = $repo->findByCategory($id, array('category' => 'asc'));
foreach ($subcategories as $subcategory) {
$result[$subcategory->getName()] = $subcategory->getId();
}
return new JsonResponse($result);
}
public function indexAction(Request $request) {
$lead = new Lead();
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
if(is_object($user)) {
$promotor = $em->getRepository('CASUsuariosBundle:Promotor')->find($user);
if (is_object($promotor)) {
$form = $this->createForm(new EventType($this->getDoctrine()->getManager()), $lead);
$template = "CASEventBundle:Default:event.html.twig";
$isPromotor = true;
}
} else {
$form = $this->createForm(new LeadType($this->getDoctrine()->getManager()), $lead);
$template = "CASEventBundle:Default:full_lead.html.twig";
$isPromotor = false;
}
if ($request->getMethod() == 'POST') {
$form->bind($request);
if ($form->isValid()) {
if($isPromotor === true) {
$type = $promotor->getType();
$name = $user->getName();
$lastname = $user->getLastName();
$email = $user->getEmail();
$password = $user->getPassword();
$phone = $user->getPhone();
$company = $promotor->getCompany();
$lead->setEventType($type);
$lead->setPromotorName($name);
$lead->setPromotorLastName($lastname);
$lead->setPromotorEmail($email);
$lead->setPromotorPhone($phone);
$lead->setPromotorCompany($company);
}
$emailReg = $form->get('promotorEmail')->getData();
$passwordReg = $form->get('promotorPassword')->getData();
$nameReg = $form->get('promotorName')->getData();
$typeReg = $form->get('promotorType')->getData();
$lastnameReg = $form->get('promotorLastName')->getData();
$phoneReg = $form->get('promotorPhone')->getData();
$companyReg = $form->get('promotorCompany')->getData();
if(!empty($emailReg) && !empty($passwordReg)) {
$userManager = $this->get('fos_user.user_manager');
$newUser = $userManager->createUser();
$newPromotor = new Promotor();
$newUser->setUsername($emailReg);
$newUser->setEmail($emailReg);
$newUser->setName($nameReg);
$newUser->setLastname($lastnameReg);
$newUser->setPhone($phoneReg);
$newUser->setIsPromotor(true);
$encoder = $this->container->get('security.password_encoder');
$encoded = $encoder->encodePassword($newUser, strval($passwordReg));
$newUser->setPassword($encoded);
$userManager->updateUser($newUser);
$newPromotor->setType($typeReg);
$newPromotor->setCompany($companyReg);
$newPromotor->setIdPromotor($newUser);
$em->persist($newUser);
$em->persist($newPromotor);
$em->persist($lead);
$em->flush();
//return $response;
}
$em->persist($lead);
$em->flush();
return $this->redirect($this->generateUrl('CASEventBundle_create'));
}
}
return $this->render($template, array('form' => $form->createView()));
}
}
you could just create a confirmation token yourself and set it to the not yet active user, send him a mail using swift wich contains a link to confirm like :
$confiToken = "123";
$url="http://url.com/confirm/$confiToken";
$user->setConfirmationToken($confiToken);
$message = $mailer->createMessage()
->setSubject('Confirm registration')
->setFrom('from#mail.com')
->setTo($sendTo)
->setBody(
$this->renderView(
'Bundle:Email:confirm.html.twig',
array(
'headline' => "Confirm your registration",
"sendTo"=>$sendTo,
"name"=>false,
"date"=>$date,
"message"=>"here ist your confirmationlink ".$url." "
)
),
'text/html'
);
$mailer->send($message);
when the user clicks the link in the email you can manually generate the token and set the user active:
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
...
$user=$em->getRepository("Bundle:User")->findOneByConfirmationToken($token);
if(!$user || $user->isEnabled()){
throw $this->createNotFoundException("link out of date");
}else {
$user->setEnabled(true);
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->get('security.context')->setToken($token);
$this->get('session')->set('_security_main',serialize($token));
$em->flush();
return $this->redirect($this->generateUrl('core_customer_dashboard'));
}