Symfony 3 Object not found error - php

I'm setting up a blog and want the homepage to show the latest blog entries including links to the single entries.
I got a link to all entries showing in a list but I can't exactly figure out how to show a single entry. Plus now I always get an "object not found" exception as soon as I try to click on the link.
Here's the controller which contents the Function to show a single entry:
<?php
// src/BlogBundle/Controller/BlogController.php
namespace BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use BlogBundle\Entity\Blog;
use BlogBundle\Entity\User;
use BlogBundle\Form\BlogType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class BlogController extends Controller
{
/**
* #Route("/blog", name="bloglist", requirements={"page": "\d+"})
*/
public function listAction()
{
$entry = $this->getDoctrine()->getRepository('BlogBundle:Blog')->findBy(array(), array('date' => 'DESC'));
dump($entry);
return $this->render('BlogBundle:blog:blog.html.twig', [
'bloglist' => $entry
]);
}
/**
* #Route("/blog/new", name="create")
*/
public function createAction(Request $request) {
$entry = new Blog();
$entry->setDate(new \DateTime('now'));
$entry->setAuthor($this->getUser());
$form = $this->createForm(BlogType::class, $entry);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$entry = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($entry);
$em->flush();
return $this->render('BlogBundle:blog:createsubmit.html.twig', array(
'entry' => $entry,
'form' => $form->createView(),
'success' => true
));
}
return $this->render('BlogBundle:blog:new.html.twig', array(
'quote' => 'New blog entry created!',
'form' => $form->createView(),
));
}
/**
* #Route("/blog/singleentry/{id}", name="singleentry", requirements={"id" = "\d+"}, defaults={"id" = 0})
*/
public function listSingleEntryAction(Request $request, Blog $blog)
{
$em = $this->getDoctrine()->getRepository('BlogBundle:Blog')->find($blog);
$form = $this->createForm(BlogType::class, $entry);
$form->handleRequest($request);
$em->persist($entry);
$em->flush();
return $this->render('BlogBundle:singleentry:edit.html.twig', array(
'entry' =>$entry,
'form' => $form->createView()
));
}
/**
* #Route("/blog/edit/{id}", name="entryedit", requirements={"id" = "\d+"}, defaults={"id" = 0})
*
*/
public function editAction(Request $request, Blog $blog) {
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($blog);
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $entry->getAuthor() == $this->getUser()->getUsername() ) {
$form = $this->createForm(BlogType::class, $entry);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em->persist($entry);
$em->flush();
return $this->render('BlogBundle:blog:editsubmit.html.twig', array(
'entry' => $entry,
'form' => $form->createView(),
'success' => true
));
}
return $this->render('BlogBundle:blog:edit.html.twig', array(
'form' => $form->createView(),
));
}
else {
echo '<div class="alert alert-danger alert-dismissable">
<span aria-hidden="true" data-dismiss="alert" class="close">×</span>
<h4>
<i class="fa fa-exclamation-circle "></i>
Only the author of an entry is allowed to edit it!</h4></div>';
return $this->listAction();
}
}
/**
* #Route("/blog/delete/{id}", name="entrydelete", requirements={"id" = "\d+"}, defaults={"id" = 0})
*
*/
public function deleteAction(Request $request, Blog $blog) {
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($blog);
if ($this->get('security.authorization_checker')->isGranted('ROLE_ADMIN') || $entry->getAuthor() == $this->getUser()->getUsername() ) {
$em->remove($entry);
$em->flush();
return $this->render('BlogBundle:blog:deletesubmit.html.twig');
}
else {
return $this->render('BlogBundle:blog:error.html.twig');
}
}
public function configureOptions(OptionsResolver $resolver) {
$resolver->setDefaults([
'data_class' => 'BlogBundle\Entity\Blog'
]);
}
}
?>
for my homepage:
<?php
namespace BlogBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
class DefaultController extends Controller {
/**
* #Route("/", name="welcome")
*/
public function indexAction() {
$entry = $this->getDoctrine()->getRepository('BlogBundle:Blog')->findBy(array(), array('date' => 'DESC'),5);
dump($entry);
return $this->render('BlogBundle:Default:index.html.twig', [
'Welcome' => 'Welcome!',
'avatar_url' => 'http://www.lufthansa.com/mediapool/jpg/45/media_789050645.jpg',
'blog' => $this->redirectToRoute('singleentry'),
'bloglist' => $entry
]);
}
}
?>
And those are the twig templates I try to render
singleentry.html.twig:
{% extends '::base.html.twig' %}
{% block body %}
<div class="container">
<div class="col-md-11">
<h1 class="page-header">{{ blog. title }}</h1>
<div class="table">
<p><span class="fa fa-clock-o"></span> Posted on {{ blog.date|date('d.M Y H:i A') }} </p>
<p><span class="fa fa-user-circle"></span> Posted by {{ blog.author }} </p>
<p>{{ blog.text }}</p>
<!-- <a class="btn btn-primary" href="#">Read More <span class="glyphicon glyphicon-chevron-right"></span></a> -->
<button type="button" class="btn btn btn-info">
Edit entry
</button>
<button type="button" class="btn btn btn-warning">
Delete entry
</button>
<hr>
</div>
</div>
</div>
{% endblock %}
for the list of blog entries on my homepage:
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title text-center">My latest blog entries</h3>
</div>
<table class="table">
{% for blog in bloglist %}
<tr>
<td>{{ blog.title }}</td>
<td width="85%" style="max-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;">
{{ blog.text }}
</td>
</tr>
{% endfor %}
</table>
</div>
edited version of listSingleEntryAction --> object shown as NULL
public function listSingleEntryAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($id);
if($entry == null)
{
$message='Entry does not exist';
return $this->render('BlogBundle:blog:error.html.twig');
}
return $this->render('BlogBundle:blog:singleentry.html.twig', Array(
'entry' => $entry,
'success' => true,
));
}

The problem is your arguments.
public function listSingleEntryAction(Request $request, Blog $blog)
{
First of all, it shouldn't be with a Blog type. It's int.
Second, rename it to $id.
And I think you have the same problem with edit and delete actions.

check out your action. First 2 lines are the reason of your problem.
/**
* #Route("/blog/singleentry/{id}", name="singleentry", requirements={"id" = "\d+"}, defaults={"id" = 0})
*/
public function listSingleEntryAction(Request $request, Blog $blog)
{
$em = $this->getDoctrine()->getManager();
$entry = $em->getRepository('BlogBundle:Blog')->find($blog);

Related

I'm trying to make a list filter in symfony using doctrine and query Builder

I am trying to build a list filter in Symfony. I'm still new to PHP, MySQL, and twig. The official documentation doesn't help a lot. It is required that I have a page with a list of all classes and next to that a search bar where the user inputs the class they want and it will show on the page without the others. I'll post my code but I think it is missing a lot of code. I only need little help and maybe sources for documentation on how to do it the official documents aren't very clear for someone with zero experience.
My ClassesRepository.php
<?php
namespace App\Repository;
use App\Entity\Classes;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* #method Classes|null find($id, $lockMode = null, $lockVersion = null)
* #method Classes|null findOneBy(array $criteria, array $orderBy = null)
* #method Classes[] findAll()
* #method Classes[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class ClassesRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Classes::class);
}
public function findbyName()
{
return $this->createQueryBuilder('c')
->getQuery()->getResult();
}
public function getSearchClasses($class){
$qb = $this->createQueryBuilder('c')
->where('c.Title LIKE :Title')
->setParameter('Title', '%' . $class->getTitle() . '%')
->orderBy('c.Title', 'DESC')
->getQuery();
}
}
classesController:
<?php
namespace App\Controller;
use App\Entity\Classes;
use App\Entity\Students;
use App\Entity\Courses;
use Symfony\Component\Form\FormTypeInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
class ClassesController extends AbstractController
{
/**
* #Route("custom/classes", name="classes_list")
*/
public function index()
{
$classes = $this->getDoctrine()->getRepository(classes::class)->findAll();
return $this->render('classes/index.html.twig', [
'classes' => $classes
]);
}
/**
* #Route("/classes/new", name="new_class")
* #Method({"GET","POST"})
*/
public function new(Request $request)
{
$class = new Classes();
$form = $this->createFormBuilder($class)
->add('Title', TextType::class, array('attr' =>
array('class' => 'form-control')))
->add('save', SubmitType::class,array('label' => 'Create',
'attr' => array('class' => 'btn btn-primary mt-3')))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$class = $form->getData();
$entityManager = $this->getDoctrine()->getManager();
$entityManager->persist($class);
$entityManager->flush();
return $this->redirectToRoute('classes_list');
}
return $this->render('classes/new.html.twig', array(
'form' => $form->createView()
));
}
/**
* #Route("/classes/edit/{id}", name="edit_class")
* #Method({"GET","POST"})
*/
public function edit(Request $request, $id)
{
$class = new Classes();
$class = $this->getDoctrine()->getRepository(classes::class)->find($id);
$form = $this->createFormBuilder($class)
->add('Title', TextType::class, array('attr' =>
array('class' => 'form-control')))
->add('save', SubmitType::class,array('label' => 'Create',
'attr' => array('class' => 'btn btn-primary mt-3')))
->getForm();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
return $this->redirectToRoute('classes_list');
}
return $this->render('classes/edit.html.twig', array(
'form' => $form->createView()
));
}
/**
* #Route("/classes/delete/{id}")
* #Method({"DELETE"})
*/
public function delete(Request $request, $id){
$class = $this->getDoctrine()->getRepository(Classes::class)->find($id);
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($class);
$entityManager->flush();
$response = new Response();
$response->send();
}
/**
* #Route("/classes/{id}", name="classes_show")
* #Method({"GET"})
*/
public function show($id){
$_class = $this->getDoctrine()->getRepository(Classes::class)->find($id);
return $this->render('classes/show.html.twig', array('classes' => $_class));
}
// /**
// * #Route("custom/classes/save")
// */
// public function save() {
// $entityManager = $this->getDoctrine()->getManager();
// $classes = new Classes();
// $classes->setTitle('Grade 2');
// $entityManager->persist($classes);
// $entityManager->flush();
// return new Response('Saved an classes with the id of '.$classes->getId());
// }
}
Index.html.twig is Location where I will need to locate the list filter
{% extends 'base.html.twig' %}
{% block title %}Classes{% endblock %}
{% block body %}
<br>
<h1>Classes:</h1>
Create
<br>
{% if classes %}
<div class="alignleft">
<table id="classes" class="table table-striped" style="width:70%">
<thead>
<tr>
<th>Class</th>
<th>Details </th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for classes in classes %}
<tr>
<td> {{ classes.title }}</td>
<td>
Show Class Details
</td>
<td>
Edit
</td>
<td>
X
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div>
<form method="GET" action="search" style = "position:absolute; left:1100px; top:150px; height:100px; width:100px">
<input type="text" name="q" placeholder="Search Query...">
<select name="column" style = "position:absolute; left:40px; top:30px; width:100px ">
<option value="classes.Title" >Class</option>
</select>
<input type="submit" class="btn btn-warning" value="Find" style = "position:absolute; left:40px; top:56px; width:100px ">
</form>
</div>
{% else %}
<p>No Classes Available</p>
{% endif %}
{% endblock %}
{% block javascripts %}
<script src="/js/classmain.js"></script>
{% endblock %}
I don't understand the behavior you expect from the filter but I hope it will help you..
In your ClassesRepository.php
// if has not $classTitle and $query it will find all
public function getSearchClasses($classTitle = null , $query=null){
$qb = $this->createQueryBuilder('c')
->orderBy('c.Title', 'DESC');
if($classTitle && $classTitle !== '') {
$qb->andWhere('c.Title LIKE :classTitle')
->setParameter('classTitle', '%' . classTitle . '%');
}
if($query && $query !== '') {
// doSomethings with query input
}
return $qb->getQuery()->getResult();
}
In your classesController:
/**
* #Route("custom/classes", name="classes_list")
*/
public function index(Request $request)
{
$classTitle = $request->query->get('classTitle',null);
$query = $request->query->get('query',null);
// if has not $classTitle and $query it will find all
$classes = $this->getDoctrine()->getRepository(classes::class)->getSearchClasses($classTitle,$query);
return $this->render('classes/index.html.twig', [
'classes' => $classes
]);
}
In your index.html.twig
// redirect to the same route that render this template ..
<form method="GET" action="{{ path('classes_list') }}">
<input type="text" name="query" placeholder="Search Query...">
<select name="classTitle">
{% for class in classes%}
<option value="{{class.title}" >{{class.title}}</option>
{% endfor %}
</select>
<input type="submit" class="btn btn-warning" value="Find">
</form>

Symfony submit multiple related forms

I'm looking to create an CRUD with multiple Entites and so multiple forms. A want to create a Site, each site on creation need to have 1 adresse, each adress need 1 City, each city need 1 Country
So I have a Controller where I called my Type
/**
* #Route("admin/sites/new", name="admin.sites.new")
* #param Request $request
* #return RedirectResponse|Response
*/
public function new (Request $request)
{
$site = new Site();
$adresse = new Adresse();
$ville = new Ville();
$pays = new Pays();
$form = $this->createForm(SiteType::class, $site);
$form2 = $this->createForm(AdresseType::class, $adresse);
$form3 = $this->createForm(VilleType::class, $ville);
$form4 = $this->createForm(PaysType::class, $pays);
$form->handleRequest($request);
$form2->handleRequest($request);
$form3->handleRequest($request);
$form4->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()
&& $form2->isSubmitted() && $form2->isValid()
&& $form3->isSubmitted() && $form3->isValid()
&& $form4->isSubmitted() && $form4->isValid()){
$this->em->persist($site);
$this->em->persist($adresse);
$this->em->persist($ville);
$this->em->persist($pays);
$this->em->flush();
$this->addFlash('success', 'Site crée avec succès');
return $this->redirectToRoute('admin.sites.index');
}
return $this->render('admin/sites/create.html.twig', [
'site' => $site,
'adresse' => $adresse,
'ville' => $ville,
'pays' => $pays,
'form' => $form->createView(),
'form2' => $form2->createView(),
'form3' => $form3->createView(),
'form4' => $form4->createView(),
]);
}
and a Twig to generate the view.
<div class="row">
<div class="col s12 m12 l12">
<div class="card-panel ">
<div class="row">
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_start(form2) }}
{{ form_widget(form2) }}
{{ form_start(form3) }}
{{ form_widget(form3) }}
{{ form_start(form4) }}
{{ form_widget(form4) }}
<button class="btn s12 m6 l3">{{ button|default('Enregister') }}</button>
{{ form_end(form) }}{{ form_end(form2) }}{{ form_end(form3) }}{{ form_end(form4) }}
</div>
</div>
</div>
</div>
My question is the next, how when i will create my Site, I could link the site_id and the address_id and so the adress_id and the city_id, the city_di and the country _id ? without separate my forms ?
I mean when I press the button the relation will be create correctly.
Thanks for you help.
This is how you should and could achieve this :
You should use embeded form How to Embed Forms
You simply create form types for your entities : SiteType, AdresseType, VilleType, PaysType and embed them like the following
// in SiteType
//....
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//...
->add('adresse', AdresseType::class)
;
}
// in AdresseType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//...
->add('ville', VilleType::class)
;
}
// in VilleType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
//...
->add('pays', PaysType::class)
;
}
Finally in your controller, all you have to do is to create
/**
* #Route("admin/sites/new", name="admin.sites.new")
* #param Request $request
* #return RedirectResponse|Response
*/
public function new (Request $request)
{
$site = new Site();
$form = $this->createForm(SiteType::class, $site);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()
$this->em->persist($site);
$this->em->flush();
$this->addFlash('success', 'Site crée avec succès');
return $this->redirectToRoute('admin.sites.index');
}
return $this->render('admin/sites/create.html.twig', [
'site' => $site,
'adresse' => $adresse,
'ville' => $ville,
'pays' => $pays,
'form' => $form->createView(),
]);
}
And the corresponding twig is :
<div class="row">
<div class="col s12 m12 l12">
<div class="card-panel ">
<div class="row">
{{ form_start(form) }}
{{ form_widget(form) }}
<button class="btn s12 m6 l3">{{ button|default('Enregister') }}</button>
{{ form_end(form) }}
</div>
</div>
</div>
</div>
Note that in order for it to work, you need to use cascade inside your entity doctrine metadata, like so :
/**
* #ORM\OneToOne(targetEntity="AppBundle:Adresse", cascade={"all"})
*/
private $adresse;
You should use embed forms : https://symfony.com/doc/current/form/embedded.html.

Laravel 5.2 Upload Image to uploads folder while user registration

I am trying to save uploaded image to uploads folder as well as database at the time of user registration, the image name is successfully saved to the database along with user details like name, address, email and etc. I am new to laravel. Please can any one suggest me, thank you.
Please find below is my register.blade.php
#extends('layouts.site')
#section('content')
<div class="login-content">
<a class="hiddenanchor" id="signup">
</a>
<a class="hiddenanchor" id="signin">
</a>
#include('layouts.site-navigation')
#include('errors.errors')
<div class="login_wrapper">
<div class="animate form login_form">
<section class="login_content">
<!-- <form> -->
<h1>Registration Form
</h1>
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm", 'files'=>'true')) !!}
<div>
</div>
<div>
{{ Form::text('username', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("username"),
'ng-model'=>'username',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.username.$touched &&
registrationForm.username.$invalid}',
'ng-minlength' => '4',
)) }}
</div>
<div>
{{ Form::text('rollnumber', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("roll number"),
'ng-minlength' => '2',
)) }}
<div>
{{ Form::text('branch', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("branch"),
'ng-minlength' => '2',
)) }}
</div>
<div>
{{ Form::text('phone', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => getPhrase("phone"),
'ng-model'=>'phone',
'ng-pattern' => getRegexPattern('phone'),
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.phone.$touched &&
registrationForm.phone.$invalid}',
'ng-minlength' => '10',
)) }}
</div>
<div>
<select id="make" name="place" class="form-control">
<option value="" disabled selected>Interested Work Place
</option>
<option value="Yemmiganur">Yemmiganur
</option>
<option value="Raichur">Raichur
</option>
</select>
</div>
<br>
<div>
Interested To Work In Night Shift:
<input type="radio" name="night_shift" value="Yes" > Yes
<input type="radio" name="night_shift" value="No"> No
</div>
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">New to site?
<a href="#signup" class="to_register"> Next
</a>
</p>
<div class="clearfix">
</div>
</div>
<br>
<a href="{{URL_USERS_LOGIN}}">
<p class="text-center">{{getPhrase('i_am_having_account')}}
</p>
</a>
</div>
</section>
<div id="register" class="animate form registration_form">
<section class="login_content">
{!! Form::open(array('url' => URL_USERS_REGISTER, 'method' => 'POST',
'name'=>'formLanguage ', 'novalidate'=>'', 'class'=>"loginform",
'name'=>"registrationForm")) !!}
<!-- <form> -->
<h1>Registration Form
</h1>
<div>
{{ Form::email('email', $value = null , $attributes =
array('class'=>'form-control formclass',
'placeholder' => getPhrase("email"),
'ng-model'=>'email',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.email.$touched &&
registrationForm.email.$invalid}',
)) }}
</div>
<div>
{{ Form::password('password', $attributes = array('class'=>'form-
control formclass instruction-call',
'placeholder' => getPhrase("password"),
'ng-model'=>'registration.password',
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.password.$touched &&
registrationForm.password.$invalid}',
'ng-minlength' => 5
)) }}
</div>
<div>
{{ Form::password('password_confirmation', $attributes =
array('class'=>'form-control formclass instruction-call',
'placeholder' => getPhrase("password_confirmation"),
'ng-model'=>'registration.password_confirmation',
'required'=> 'true',
'ng-class'=>'{"has-error":
registrationForm.password_confirmation.$touched &&
registrationForm.password_confirmation.$invalid}',
'ng-minlength' => 5,
'compare-to' =>"registration.password"
)) }}
{{ Form::text('aadhar_number', $value = null , $attributes =
array('class'=>'form-control',
'placeholder' => "UID (Aadhaar)",
'required'=> 'true',
'ng-class'=>'{"has-error": registrationForm.aadhar_number.$touched
&& registrationForm.aadhar_number.$invalid}',
'ng-minlength' => '12',
)) }}
<br>
</div>
<fieldset class="form-group" >
<input type="file" class="form-control" name="image"
accept=".png,.jpg,.jpeg" id="image_input">
</fieldset>
<?php $parent_module = getSetting('parent', 'module'); ?>
#if(!$parent_module)
<input type="hidden" name="is_student" value="0">
#else
<div class="row">
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_an_admin')}}
</label>
</div>
<div class="col-md-6">
{{ Form::radio('is_student', 0, true, array('id'=>'free')) }}
<label for="free">
<span class="fa-stack radio-button">
<i class="mdi mdi-check active">
</i>
</span> {{getPhrase('i_am_a_student')}}
</label>
</div>
</div>
#endif
<div class="text-center buttons">
<button type="submit" class="btn btn-default submit"
ng-disabled='!registrationForm.$valid'>
{{getPhrase('register_now')}}
</button>
</div>
{!! Form::close() !!}
<div class="clearfix">
</div>
<div class="separator">
<p class="change_link">Already a member ?
<a href="#signin" class="to_register"> Previous
</a>
</p>
<div class="clearfix">
</div>
</div>
</section>
</div>
</div>
#stop
#section('footer_scripts')
#include('common.validations')
#stop
AuthController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Validator;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use \Auth;
use Socialite;
use Exception;
class AuthController extends Controller
{
/*
|--------------------------------------------------------------------------
| Registration & Login Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users, as well as the
| authentication of existing users. By default, this controller uses
| a simple trait to add these behaviors. Why don't you explore it?
|
*/
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
/**
* Where to redirect users after login / registration.
*
* #var string
*/
protected $redirectTo = '/';
protected $dbuser = '';
protected $provider = '';
/**
* Create a new authentication controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware($this->guestMiddleware(), ['except' => 'logout']);
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'username' => 'required|max:255|unique:users',
// 'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'aadhar_number' => 'required|max:12|unique:users',
'password' => 'required|min:6|confirmed',
'image' => 'bail',
'place' => 'required',
'night_shift' => 'required',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data )
{
$type = 'student';
if($data['is_student'])
$type = 'parent';
$role = getRoleData($type);
$user = new User();
$user->username = $data['username'];
$user->rollnumber = $data['rollnumber'];
$user->branch = $data['branch'];
$user->email = $data['email'];
$user->password = bcrypt($data['password']);
$user->role_id = $role;
$user->image = $data['image'];
$user->place = $data['place'];
$user->night_shift = $data['night_shift'];
$user->phone = $data['phone'];
$user->aadhar_number = $data['aadhar_number'];
$user->slug = $user->makeSlug($user->username);
$user->save();
$user->roles()->attach($user->role_id);
try{
$this->sendPushNotification($user);
sendEmail('registration', array('user_name'=>$user->name,
'username'=>$data['username'], 'to_email' => $user->email,
'password'=>$data['password'], 'aadhar_number' => $user->aadhar_number));
}
catch(Exception $ex)
{
}
flash('success','record_added_successfully', 'success');
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
return $user;
}
public function sendPushNotification($user)
{
if(getSetting('push_notifications', 'module')) {
if(getSetting('default', 'push_notifications')=='pusher') {
$options = array(
'name' => $user->name,
'image' => getProfilePath($user->image),
'slug' => $user->slug,
'role' => getRoleData($user->role_id),
);
pushNotification(['owner','admin'], 'newUser', $options);
}
else {
$this->sendOneSignalMessage('New Registration');
}
}
}
/**
* This is method is override from Authenticate Users class
* This validates the user with username or email with the sent password
* #param Request $request [description]
* #return [type] [description]
*/
protected function processUpload(Request $request, User $user)
{
if(env('DEMO_MODE')) {
return 'demo';
}
if ($request->hasFile('image')) {
$imageObject = new ImageSettings();
$destinationPath = $imageObject->getProfilePicsPath();
$destinationPathThumb = $imageObject->getProfilePicsThumbnailpath();
$fileName = $user->id.'.'.$request->image->guessClientExtension();
;
$request->file('image')->move($destinationPath, $fileName);
$user->image = $fileName;
Image::make($destinationPath.$fileName)->fit($imageObject-
>getProfilePicSize())->save($destinationPath.$fileName);
Image::make($destinationPath.$fileName)->fit($imageObject-
>getThumbnailSize())->save($destinationPathThumb.$fileName);
$user->save();
}
}
public function postLogin(Request $request)
{
$login_status = FALSE;
if (Auth::attempt(['aadhar_number' => $request->email, 'password' =>
$request->password])) {
// return redirect(PREFIX);
$login_status = TRUE;
}
elseif (Auth::attempt(['email'=> $request->email, 'password' =>
$request->password])) {
$login_status = TRUE;
}
if(!$login_status)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
/**
* Check if the logged in user is parent or student
* if parent check if admin enabled the parent module
* if not enabled show the message to user and logout the user
*/
if($login_status) {
if(checkRole(getUserGrade(7))) {
if(!getSetting('parent', 'module')) {
return redirect(URL_PARENT_LOGOUT);
}
}
}
/**
* The logged in user is student/admin/owner
*/
if($login_status)
{
return redirect(PREFIX);
}
}
/**
* Redirect the user to the GitHub authentication page.
*
* #return Response
*/
public function redirectToProvider($logintype)
{
if(!getSetting($logintype.'_login', 'module'))
{
flash('Ooops..!', $logintype.'_login_is_disabled','error');
return redirect(PREFIX);
}
$this->provider = $logintype;
return Socialite::driver($this->provider)->redirect();
}
/**
* Obtain the user information from GitHub.
*
* #return Response
*/
public function handleProviderCallback($logintype)
{
try{
$user = Socialite::driver($logintype);
if(!$user)
{
return redirect(PREFIX);
}
$user = $user->user();
if($user)
{
if($this->checkIsUserAvailable($user)) {
Auth::login($this->dbuser, true);
flash('Success...!', 'log_in_success', 'success');
return redirect(PREFIX);
}
flash('Ooops...!', 'faiiled_to_login', 'error');
return redirect(PREFIX);
}
}
catch (Exception $ex)
{
return redirect(PREFIX);
}
}
public function checkIsUserAvailable($user)
{
$id = $user->getId();
$nickname = $user->getNickname();
$name = $user->getName();
$email = $user->getEmail();
$avatar = $user->getAvatar();
$this->dbuser = User::where('email', '=',$email)->first();
if($this->dbuser) {
//User already available return true
return TRUE;
}
$newUser = array(
'name' => $name,
'email'=>$email,
);
$newUser = (object)$newUser;
$userObj = new User();
$this->dbuser = $userObj->registerWithSocialLogin($newUser);
$this->dbuser = User::where('slug','=',$this->dbuser->slug)->first();
// $this->sendPushNotification($this->dbuser);
return TRUE;
}
public function socialLoginCancelled(Request $request)
{
return redirect(PREFIX);
}
}
First, you should urgently consider updating Laravel to newer versions.
Second, I think you are missing enctype="multipart/form-data" accept-charset="UTF-8" in your form tag

symfony 4 create many to many relation and embeded form not work correctly

I create two entity. first Posts and second categories. this to entity have many to many relation.
I make a form from posts and add an embed form categories that use ChoiceType.
the form work correctly an I can add as many as categories to each post.
but in database orm create an posts_categories when I look to its data the posts_id is correct and from posts table but I don't know where the categories_id come from ?
I means the real id of categories not save on posts_categories table. where does this id come? and how I can config that real id save on table?
App\Entity\Posts.php
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\PostsRepository")
*/
class Posts
{
public $newFormTitle = 'Add New Post';
public $editFormTitle = 'Edit Post';
public $listFormTitle = 'Posts List';
public $adminList = 'postList';
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=200)
*/
private $title;
/**
* #ORM\Column(type="text")
*/
private $content;
/**
* #ORM\ManyToMany(targetEntity="App\Entity\Categories" , orphanRemoval=true, cascade={"persist"})
*/
private $categories;
public function __construct()
{
$this->categories = new ArrayCollection();
}
public function getId()
{
return $this->id;
}
public function getTitle(): ?string
{
return $this->title;
}
public function setTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getContent(): ?string
{
return $this->content;
}
public function setContent(?string $content): self
{
$this->content = $content;
return $this;
}
/**
* #return Collection|Categories[]
*/
public function getCategories(): Collection
{
return $this->categories;
}
public function addCategory(Categories $category): self
{
if (!$this->categories->contains($category)) {
$this->categories[] = $category;
}
return $this;
}
public function removeCategory(Categories $category): self
{
if ($this->categories->contains($category)) {
$this->categories->removeElement($category);
}
return $this;
}
}
App\Entity\Categories.php
<?php
namespace App\Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass="App\Repository\CategoriesRepository")
*/
class Categories
{
public $newFormTitle = 'Add New Post';
public $editFormTitle = 'Edit Post';
public $listFormTitle = 'Categories List';
public $adminList = 'categoriesList';
/**
* #ORM\Id()
* #ORM\GeneratedValue()
* #ORM\Column(type="integer")
*/
private $id;
/**
* #ORM\Column(type="string", length=100)
*/
private $name;
public function __construct()
{
}
public function getId()
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
}
App\Form\PostsType.php
<?php
namespace App\Form;
use App\Entity\Posts;
use App\Form\CategoriesPostsType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
class PostsType extends AbstractType
{
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('title', null, [
'attr' => ['autofocus' => true ,'class'=>'form-control'],
'label' => 'label.title',
'label_attr' => ['class'=>'label-control'],
])
->add('content', null, [
'attr' => ['rows' => 8 ,'class'=>'form-control'],
'label' => 'label.content',
'label_attr' => ['class'=>'label-control'],
])
;
/*
$builder->add('categories', CollectionType::class, array(
'entry_type' => CategoryType::class,
'entry_options' => array('label' => false),
'allow_add' => true,
));
*/
$builder->add('categories', CollectionType::class, array(
'entry_type' => CategoriesPostsType::class,
'entry_options' => array('label' => false),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => true,
'label' => false,
));
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Posts::class,
]);
}
}
App\Form\CategoriesPostsType.php
<?php
namespace App\Form;
use App\Entity\Categories;
use App\Form\Type\CategoryInputType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use App\Repository\CategoriesRepository;
class CategoriesPostsType extends AbstractType
{
private $categories;
public function __construct(CategoriesRepository $category)
{
$categories = $category->findAll();
$choise = array();
foreach ($categories as $key => $value)
//$choise[] = new Categories($categories[$key]->getId();
$choise[$categories[$key]->getName()] = $categories[$key]->getId();
$this->categories = $choise;
}
/**
* {#inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', ChoiceType::class, [
'attr' => ['autofocus' => true ,'class'=>'form-detail-control formChoiceType'],
'label' => false,
'label_attr' => ['class'=>'label-control'],
'choices' => $this->categories,
])
/* ->add('category', CategoryInputType::class, [
'label' => 'label.category',
'required' => false,
])*/
;
}
/**
* {#inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => Categories::class,
]);
}
}
twig form
{% extends 'theme/basickTheme/form.html.twig' %}
{% block body_id 'content_new_posts' %}
{% block defaultFormHeader entity.newFormTitle %}
{% block defaultFormBody %}
<div class="row">
<div class="col-12">
{{ form_start(form) }}
<div class="col-12">
{{ form_errors(form) }}
</div>
<div class="col-12">
{{ form_row(form.title) }}
</div>
<div class="col-12">
{{ form_row(form.content) }}
</div>
<div class="col-12 form-group">
<h3>Categories</h3>
</div>
<div class="col-12">
<button type="button" class="btn add-detail-botton" onclick="addCategoriesForm(1)">
<img src="{{ asset('img/custum-icon/add-small.png') }}">
<i class="fa fa-save" aria-hidden="true"></i> {{ button_label|default('categories.label.add.category'|trans) }}
</button>
<ol class="detail-list" data-prototype="{{ form_widget(form.categories.vars.prototype)|e('html_attr') }}">
{# iterate over each existing tag and render its only field: name #}
{% for Category in form.categories %}
<li>{{ form_widget(Category.name) }}</li>
{% endfor %}
</ol>
<button type="button" class="btn add-detail-botton" onclick="addCategoriesForm(2)">
<img src="{{ asset('img/custum-icon/add-small.png') }}">
<i class="fa fa-save" aria-hidden="true"></i> {{ button_label|default('categories.label.add.category'|trans) }}
</button>
</div>
<div class="col-12 form-footer-botton">
<button type="submit" class="btn btn-primary">
<i class="fa fa-save" aria-hidden="true"></i> {{ button_label|default('Label.save'|trans) }}
</button>
<a href="{{ backUrl }}" class="btn btn-primary">
<i class="fa fa-list-alt" aria-hidden="true"></i> {{ 'Label.back.to.list'|trans }}
</a>
</div>
{{ form_end(form) }}
</div>
</div>
{% endblock %}
{% block javascripts %}`
<script>
var $collectionHolder;
jQuery(document).ready(function() {
// Get the ul that holds the collection of tags
$collectionHolder = $('ol.detail-list');
$collectionHolder.find('li').each(function() {
addCategoriesFormDeleteLink($(this));
});
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
});
function addCategoriesForm( $appendType = 1) {
var $collectionHolder = $('ol.detail-list');
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
var newForm = prototype;
// You need this only if you didn't set 'label' => false in your tags field in TaskType
// Replace '__name__label__' in the prototype's HTML to
// instead be a number based on how many items we have
// newForm = newForm.replace(/__name__label__/g, index);
// Replace '__name__' in the prototype's HTML to
// instead be a number based on how many items we have
newForm = newForm.replace(/__name__/g, index);
newForm = newForm.replace(/form-detail-control/g, 'form-detail-control-new');
// increase the index with one for the next item
$collectionHolder.data('index', index + 1);
// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi = $('<li class="prototye"></li>').prepend(newForm);
if($appendType == 1)
$collectionHolder.prepend($newFormLi);
else
$collectionHolder.append($newFormLi);
//$newLinkLi.before($newFormLi);
addCategoriesFormDeleteLink($newFormLi);
}
function addCategoriesFormDeleteLink($tagFormLi) {
//var $removeFormButton = $('<button type="button" class="detailDeleteButton">Delete</button>');
var $removeFormButton = $('<button type="button" class="btn delte-detail-botton"><img src="{{ asset('img/custum-icon/delete-smal.png') }}"><i class="fa fa-save" aria-hidden="true"></i>{{ button_label|default('categories.label.delete.category'|trans) }}</button>');
$tagFormLi.append($removeFormButton);
$removeFormButton.on('click', function(e) {
// remove the li for the tag form
$tagFormLi.remove();
});
}
</script>
{% endblock %}

Laravel display name from database

I have a new problem. I'll try to give enough information.
I'm trying to display the names of the employees that have visited the customers, but as you can see it displays the names of the customers. Instead of Bryan or Granucci (these are the customers), it should say Madmin (I have only one user at the moment).
Screenshot
This is the drafts page
I'll add the code form my view, controller and model.
Drafts View
#extends('app')
#section('content')
#include('nav')
<div class="container">
#include('flash')
<div class="row">
<div class="col-md-2">
{!! Form::open(['method' => 'GET', 'action' => 'DraftsController#create']) !!}
{!! Form::submit('Create new draft', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::close() !!}
</div>
</div>
<hr>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-heading">Search drafts</div>
<div class="panel-body">
{!! Form::open(array('url' => 'drafts/search', 'method' => 'post')) !!}
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('customer_name', 'Customer:') !!}
</div>
<div class="col-md-6">
{!! Form::text('customer_name', null, ['class' => 'form-control typeahead tt-query', 'autocomplete' => 'off', 'spellcheck' => 'false', 'placeholder' => 'Search...']) !!}
</div>
<div class="col-md-2" align="right">
{!! Form::label('customer_id', 'Customer ID:') !!}
</div>
<div class="col-md-2">
{!! Form::text('customer_id', null, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('descr', 'Article:') !!}
</div>
<div class="col-md-6">
{!! Form::text('descr', null, ['class' => 'form-control typeahead tt-query', 'autocomplete' => 'off', 'spellcheck' => 'false', 'placeholder' => 'Search...']) !!}
{!! Form::hidden('reportgroup', null, ['class' => 'form-control']) !!}
</div>
<div class="col-md-2" align="right">
{!! Form::label('article_id', 'Article ID:') !!}
</div>
<div class="col-md-2">
{!! Form::text('article_id', null, ['class' => 'form-control', 'readonly' => 'readonly']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-2" align="right">
{!! Form::label('reference', 'Reference:') !!}
</div>
<div class="col-md-10">
{!! Form::text('reference', null, ['class' => 'form-control']) !!}
</div>
</div>
<br><br>
<div class="form-group">
<div class="col-md-12" align="right">
{!! Form::submit('Search', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
#include('errors')
</div>
</div>
<div class="panel panel-default">
{!! Form::open(['method' => 'POST', 'action' => 'DraftsController#invoice']) !!}
<div class="panel-heading">Search results</div>
<div class="panel-body">
<table class="table">
<tr>
<th> </th>
<th>No</th>
<th>Employee</th>
<th>Customer</th>
<th>Reference</th>
<th>Draft created</th>
<th>Work date</th>
<th style="text-align:right">Total excl. VAT</th>
<th> </th>
</tr>
<?php $count = 0; ?>
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
</table>
<?php
if ($count == 0) {
print "No results";
}
else {
?>
<table>
<tr>
<td>
{!! Form::submit('Create invoice for selected drafts', ['class' => 'btn btn-primary form-control']) !!}
</td>
<td>
with invoice date
</td>
<td>
<input class="form-control" name="createDate" type="date" id="createDate" value="{{date('Y-m-d')}}">
</td>
<td>
and mail them to customer
</td>
<td>
<input type="checkbox" id="mailThem" name="mailThem">
</td>
</tr>
</table>
{!! Form::close() !!}
<?php
}
?>
</div>
</div>
</div>
</div>
</div>
#include('jsonArticles')
#include('jsonCustomers')
<script src="{{ asset('/js/typeahead.js') }}"></script>
<script src="{{ asset('/js/customers.js') }}"></script>
<script src="{{ asset('/js/articles.js') }}"></script>
#stop
Draftsheader Model
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class DraftHeader extends Model {
public function customer()
{
return $this->belongsTo('App\Customer');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function lines()
{
return $this->hasMany('App\DraftLine');
}
protected $fillable = [
'user_id',
'employee_name',
'customer_id',
'name',
'name2',
'address',
'postcode',
'town',
'country',
'reference'
];
}
Drafts Controller
<?php
namespace App\Http\Controllers;
use Session;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Article;
use App\Customer;
use App\User;
use App\DraftHeader;
use App\DraftLine;
use App\InvoiceHeader;
use App\InvoiceLine;
use App\InvoiceMail;
use App\Http\Requests\DraftRequest;
use App\Http\Requests\DraftSearchRequest;
use App\Http\Requests\DraftLinesRequest;
use App\Http\Controllers\Controller;
use Carbon\Carbon;
class DraftsController extends Controller {
/*
|--------------------------------------------------------------------------
| ArticlesController
|--------------------------------------------------------------------------
|
| Controller for Metis draft tasks
|
*/
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct() {
$this->middleware('auth:admin');
}
/**
* Get all articles
*
* #return array()
*/
private function allArticles() {
$allArticles = array();
$ff = Article::All()->toArray();
foreach ($ff as $ff1) {
$allArticles[] = array('name' => $ff1['descr'], 'id' => $ff1['id']);
}
return $allArticles;
}
/**
* Get all customers
*
* #return array()
*/
private function allCustomers() {
$allCustomers = array();
$ff = Customer::All()->toArray();
foreach ($ff as $ff1) {
$allCustomers[] = array('name' => $ff1['name'], 'id' => $ff1['id']);
}
return $allCustomers;
}
/**
* Get all uers
*
* #return array()
*/
private function allUsers() {
$allUsers = array();
$ff = User::All()->toArray();
foreach ($ff as $ff1) {
$allUsers[] = array('name' => $ff1['name'], 'id' => $ff1['id']);
//dd($allUsers);
}
return $allUsers;
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index() {
// Use request saved in session if applicable
$result = array();
if (Session::has('draft_search_request')) {
$request = Session::get('draft_search_request');
//dd($request);
$result = DraftHeader::query();
if (strlen(trim($request['customer'])) > 0) {
$result->where('name', 'LIKE', "%" . $request['customer'] . "%");
}
if (strlen(trim($request['user'])) > 0) {
$result->where('name', 'LIKE', "%" . $request['user'] . "%");
}
if (strlen(trim($request['reference'])) > 0) {
$result->where('reference', 'LIKE', "%" . $request['reference'] . "%");
}
if (strlen(trim($request['article'])) > 0) {
$result->DraftLine()->where('descr', 'LIKE', "%" . $request['article'] . "%");
}
//dd($result->toSql());
$result = $result->get()->toArray();
//dd($result);
}
else {
$result = DraftHeader::query()->where('created_at', '>', Carbon::yesterday())->get()->toArray();
}
// Get the total amount for each draft draft
$totals = array();
foreach ($result as $value) {
$total = DraftLine::selectRaw('sum(qty*netamount) AS total')->where('draft_header_id', '=', $value['id'])->get()->toArray();
$totals[$value['id']] = $total[0]['total'];
}
return view('drafts.search')->with('result', $result)->with('totals', $totals)->with('allArticles', $this->allArticles())->with('allCustomers', $this->allCustomers())->with('allUsers', $this->allUsers());
}
public function search(DraftSearchRequest $request) {
//Put request in session variable to use in view
$request1 = array('customer' => $request['customer'],'user' => $request['user'], 'reference' => $request['reference'], 'article' => $request['article']);
if ($request1['customer'] == "" && $request1['user'] == "" && $request1['reference'] == "" && $request1['article'] == "") {
session()->flash('draft_search_request', $request1);
}
else {
Session::put('draft_search_request', $request1);
}
return redirect ('drafts');
}
public function invoice(Request $request) {
//Create invoices for the selected drafts
//dd($request);
//dd($request->except('_token'));
$number_of_invoices = 0;
$draftdeleted = false;
$mail = false;
if (isset($request['mailThem']) && $request['mailThem'] == "on") {
$mail = true;
}
$invoicedate = $request['createDate'];
if (!checkdate(substr($invoicedate, 5, 2), substr($invoicedate, 8, 2), substr($invoicedate, 0, 4))) {
$invoicedate = "";
}
foreach($request->except('_token') as $key => $val) {
//dd($key);
if (substr($key, 0, 8) == "invoice_" && $val == "on") {
$draft_id = substr($key, 8);
// Create the invoice
// But only if there are lines
$draftheader = DraftHeader::findOrFail($draft_id)->toArray();
$draftlines = DraftHeader::findOrFail($draft_id)->lines()->get()->toArray();
if (count($draftlines) > 0) {
// Create the invoice header
$invoiceheader = InvoiceHeader::create($draftheader);
if ($invoicedate != "") {
$invoiceheader->created_at = $invoicedate;
$invoiceheader->save();
}
// Create the invoice lines
foreach ($draftlines as $draftline) {
$newline = new InvoiceLine;
$newline->article_id = $draftline['article_id'];
$newline->descr = $draftline['descr'];
$newline->qty = $draftline['qty'];
$newline->grossamount = $draftline['grossamount'];
$newline->discount = $draftline['discount'];
$newline->netamount = $draftline['netamount'];
$newline->taxrate = $draftline['taxrate'];
$newline->addition = $draftline['addition'];
$newline = $invoiceheader->lines()->save($newline);
}
// Delete the draft
DraftHeader::destroy($draft_id);
$number_of_invoices++;
if ($mail) {
// Add the invoice to the create and send queue (no recipient = to be processed)
$invoicemail = new InvoiceMail;
$invoicemail = $invoiceheader->mail()->save($invoicemail);
}
}
}
if (substr($key, 0, 7) == "delete_") {
// Delete the selected draft
$draft_id = substr($key, 7);
DraftHeader::destroy($draft_id);
session()->flash('flash_success', "Draft deleted");
$draftdeleted = true;
}
}
$andmailed = "";
if ($number_of_invoices > 0 && $mail) {
$andmailed = " and queued to be sent by mail";
}
if (!$draftdeleted) {
session()->flash('flash_success', $number_of_invoices . " invoice(s) created " . $andmailed);
}
$request1 = array('customer' => $request['customer'], 'user' => $request['user'], 'reference' => $request['reference'], 'article' => $request['article']);
if ($request1['customer'] == "" && ['user'] == "" && $request1['reference'] == "" && $request1['article'] == "") {
session()->flash('draft_search_request', $request1);
}
else {
Session::put('draft_search_request', $request1);
}
return redirect ('drafts');
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create() {
return view('drafts.create')->with('allCustomers', $this->allCustomers());
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store(DraftRequest $request) {
//dd($request);
// Get the customer information
/*
$this->validate($request, [
'reference' => 'required'
]);
*
*/
$customer = Customer::findOrFail($request['customer_id']);
$pass = array_merge($request->all(), $customer->toArray());
//dd($pass);
DraftHeader::create($pass);
//dd($request);
// Get the user information
/*
$this->validate($request, [
'reference' => 'required'
]);
*
*/
$user = User::findOrFail($request['user_id']);
$pass = array_merge($request->all(), $user->toArray());
//dd($pass);
DraftHeader::create($pass);
return redirect('drafts');
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id) {
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id) {
// Retrieve header and lines
//dd($id);
$draftheader = DraftHeader::findOrFail($id)->toArray();
//dd($draftheader);
$draftlines = DraftHeader::findOrFail($id)->lines()->get()->toArray();
//dd($draftlines);
// Get the draft's total
$drafttotal = 0;
$drafttotal_in = 0;
foreach ($draftlines as $line) {
$drafttotal = $drafttotal + ($line['qty'] * $line['netamount']);
$drafttotal_in = $drafttotal_in + (($line['qty'] * $line['netamount']) / 100 * (100 + $line['taxrate']));
}
return view('drafts.edit')->with('header', $draftheader)->with('lines', $draftlines)->with('drafttotal', $drafttotal)->with('drafttotal_in', $drafttotal_in)->with('allArticles', $this->allArticles());
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id, DraftLinesRequest $request) {
//dd($request->all());
// Save the draft header (again)
$draftheader = DraftHeader::findOrFail($id);
if ($draftheader->reference != $request['reference']) {
$draftheader->reference = $request['reference'];
$draftheader->save();
}
// Update the lines if there are changes
$requestcopy = $request->All();
reset($requestcopy);
foreach ($requestcopy as $key => $value) {
if (substr($key, 0, 11) == "grossamount") {
$lineid = substr($key, 11);
$draftline = Draftline::findOrFail($lineid);
$v_descr = 'descr' . $lineid;
$v_qty = 'qty' . $lineid;
$v_grossamount = 'grossamount' . $lineid;
$v_discount = 'discount' . $lineid;
$v_addition = 'addition' . $lineid;
if ($draftline->descr != $request[$v_descr] || $draftline->qty != $request[$v_qty] || $draftline->grossamount != $request[$v_grossamount] || $draftline->discount != $request[$v_discount] || $draftline->addition != $request[$v_addition]) {
$draftline->descr = $request[$v_descr];
$draftline->qty = $request[$v_qty];
$draftline->addition = $request[$v_addition];
$draftline->grossamount = $request[$v_grossamount];
$draftline->discount = $request[$v_discount];
$draftline->netamount = $draftline->grossamount - ($draftline->grossamount * ($draftline->discount/100)) + ($draftline->grossamount * ($draftline->addition/100));
$draftline->save();
session()->flash('flash_success', 'Update succeeded');
}
}
}
// Check if a line needs to be deleted
reset($requestcopy);
foreach ($requestcopy as $key => $value) {
if (substr($key, 0, 6) == "cmdDel") {
$lineid = substr($key, 6);
$draftline = Draftline::findOrFail($lineid);
$draftline->delete();
session()->flash('flash_success', 'Draft line was deleted');
}
}
// Check if a new line should be created
if ($request['qty'] != 0 && $request['article_id'] > 0 && strlen($request['descr']) > 0) {
$newline = new DraftLine;
$article = Article::findOrFail($request['article_id']);
$customer = $draftheader->customer;
$newline->article_id = $request['article_id'];
$newline->descr = $request['descr'];
$newline->qty = $request['qty'];
$newline->grossamount = $article->gross;
$newline->discount = $customer->discount;
$newline->taxrate = $article->taxrate;
if ($customer->taxrate == "No tax") {
$newline->taxrate = 0;
}
$newline->netamount = $newline->grossamount - ($newline->grossamount * ($newline->discount/100));
$newline = $draftheader->lines()->save($newline);
session()->flash('flash_success', 'New draft line was added');
}
return redirect('drafts/' . $id . '/edit');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id) {
//
}
}
User model
<?php namespace App;
use App\Hour;
use Illuminate\Notifications\Notifiable;
use Illuminate\Auth\Authenticatable;
use Sofa\Eloquence\Eloquence;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
use Notifiable;
use Eloquence;
public function draftheaders()
{
return $this->hasMany('App\DraftHeader');
}
protected $searchableColumns = ['name'];
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function hours()
{
return $this->hasMany(Hour::class);
}
}
User controller
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
public function find(Request $request)
{
$term = trim($request->q);
if (empty($term)) {
return \Response::json([]);
}
$users = user::search($term)->limit(5)->get();
$formatted_users = [];
foreach ($users as $user) {
$formatted_users[] = ['id' => $user->id, 'text' => $user->name];
}
return \Response::json($formatted_users);
}
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth')->except('find');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('user');
}
}
The database has the following tables:
User table,
Draftsheader table
In the draftsheader table I changed the column user_id to index. And
in the users table I changed column name to index. Normally I would
index the column and give it a foreignkey. But I looked at the
customer table and the draftsheader table and there where no
foreignkeys. So I was thinking maybe foreignkeys arent nessecary, as
long as the fields are indexed.
I hope you guys can help me out, cause i'm stuck... If information is missing let me now and I'll edit the page.
Update
In the view I changed [¨name¨] to [¨employee_name¨] Like suggested by a fellow stackoverflow user. It resulted in this:
Changed name to employee_name
Try changing this:
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
To this:
#foreach ($result as $draft)
<tr>
<td><input type="checkbox" id="invoice_{{$draft['id']}}" name="invoice_{{$draft['id']}}"></td>
<td>{{ $draft['id'] }}</td>
<td>{{$draft['employee_name'] }} ({{ $draft['user_id'] }})</td>
<td>{{$draft['name'] }} ({{ $draft['customer_id'] }})</td>
<td>{{ $draft['reference'] }}</td>
<td>{{ $draft['created_at'] }}</td>
<td></td>
<td style="text-align:right">{{ number_format($totals[$draft['id']],2) }}</td>
<td><input class="btn btn-danger" name="delete_{{$draft['id']}}" id="delete_{{$draft['id']}}" type="submit" value="X"></td>
</tr>
<?php $count++ ?>
#endforeach
You use ['name'] two times, but you have the customer_name on it.

Categories