Hello im triying to get on my dashboard only the most recent articles
but isnt working i did this function
public function PostsRecientes(){
return $this->getEntityManager()
->createQuery('
SELECT post
FROM App:Posts post
WHERE post.fechaPublicacion > CURRENT_DATE()')
->getResult();
}
and this in my dashboardcontroller
/**
* #Route("/", name="dashboard")
*/
public function index(PaginatorInterface $paginator, Request $request): Response
{
$em = $this->getDoctrine()->getManager();
$posts = $em->getRepository(Posts::class)->PostsRecientes();
return $this->render('dashboard/index.html.twig', [
'posts' => $posts
]);
}
but when i do a var dump i doesnt bring any post.
You can use setFirstResult and setMaxResults, for example:
public function PostsRecientes()
{
$qb = $this->createQueryBuilder('p')
->orderBy('p.id', 'DESC')
->setFirstResult(0)
->setMaxResults(6);
return $qb->getQuery()->getResult();
}
Related
i am using laravel 7 eloquent. i am very new to laravel
this is basic method i am getting data from category table
public function category(){
$category = Category::orderBy('id', 'desc')->get();
$data['pageData'] = $category;
$data['pageTitle'] = "Category";
return view('admin.category.index')->with('data',$data);
}
But i want to do something like this
public function category(){
$category = Category::orderBy('id', 'desc')->get();
if(!empty($_REQUEST['parent_id']))
$category->where('parent_id',$_REQUEST['parent_id']);
$data['pageData'] = $category;
$data['pageTitle'] = "Category";
return view('admin.category.index')->with('data',$data);
}
So how can this is possible using eloquent.
Any help out of this question are helpful for me as i am beginner.
Try this
public function category(){
$query = Category::orderBy('id','desc');
$query = where('parent_id',$_REQUEST['parent_id']);
$category = $query->get();
$data['pageData'] = $category;
$data['pageTitle'] = 'Category';
return view('admin.category.index')->with('data',$data);
}
You can leverage the when() eloquent method to add conditional clause to query:
public function category()
{
$category = Category::when(request('parent_id'),function($parent_id,$query)
{
$query->where('parent_id',$parent_id);
})->orderBy('id', 'desc')->get();
$data['pageData'] = $category;
$data['pageTitle'] = "Category";
return view('admin.category.index')->with('data',$data);
}
when() doc reference https://laravel.com/docs/8.x/queries#conditional-clauses
You can use the when method to only apply the query if the request contains the parent_id.
From the docs:
Sometimes you may want certain query clauses to apply to a query based
on another condition. For instance, you may only want to apply a where
statement if a given input value is present on the incoming HTTP
request. You may accomplish this using the when method:
$role = $request->input('role');
$users = DB::table('users')
->when($role, function ($query, $role) {
return $query->where('role_id', $role);
})
->get();
The when method only executes the given closure when the first
argument is true. If the first argument is false, the closure will not
be executed. So, in the example above, the closure given to the when
method will only be invoked if the role field is present on the
incoming request and evaluates to true.
In your case it would be the following:
use Illuminate\Http\Request;
public function category(Request $request)
{
$categories = Category::query()
->when($request->input('parent_id'), function ($query, $parent_id) {
$query->where('parent_id', $parent_id);
})
->orderBy('id', 'desc')
->get();
$data['pageData'] = $categories;
$data['pageTitle'] = "Category";
return view('admin.category.index')->with('data', $data);
}
You can do as like below
public function category(){
$category = new Category();
if(!empty($_REQUEST['parent_id'])){
$category->where('parent_id',$_REQUEST['parent_id']);
}
$category = $category->orderBy('id', 'desc')->get()
$data['pageData'] = $category;
$data['pageTitle'] = "Category";
return view('admin.category.index')->with('data',$data);
}
Try using laravel when condition
https://laravel.com/docs/8.x/queries#conditional-clauses
Improve your question with proper details. as you mention in the question the second coding path won't work because it doesn't have $request query to functionally run the if statement. anyhow if you want to get only pageData & pageTitle in laravel Eloquent ORM you have to select both columns as follows.
class CategoryController extends Controller
{
public function category(){
$category = Category::select('pageData', 'pageTitle')->orderBy('id', 'desc')->get();
return view('admin.category.index')->with('data', $category);
}
}
I have this query filter which works fine to query out the result. For example, if I need to find books which have the Author name something:
Book::with('user', 'author')
->whereHas('author', function ($query) use($filters) {
$query->filter($filters);
})->paginate(30);
But the thing is if I want to order the Books by the author names. I this case nothing happens.
How can I sort books by author name?
QueryFilter looks like this:
public function __construct(Request $request) {
$this->request = $request;
$this->filterService = new FilterService();
}
public function apply(Builder $builder) {
$this->builder = $builder;
foreach ($this->filters() as $name => $value) {
if (method_exists($this, $name)) {
call_user_func_array([$this, $name], array_filter([$value]));
}
}
return $this->builder;
}
public function filters() {
return $this->filterService->removeEmptyFieldsFromRequest($this->request);
}
And the book filter looks like this:
public function date($date) {
return $this->builder->where('date', $date);
}
public function name_sort($order = 'asc') {
return $this->builder->orderBy('name', $order);
}
You can use class join statement :
$books = Book::select('author.name AS author_name, countries.*')
->with('user')
->join('author', 'author.id', '=', 'book.author_id')
->orderBy('author.name', 'ASC')
->paginate(10);
I have created a search form,i'm trying to fetch the following data from the database (airport,airport1,departuredate,price),i can only get [airport] but not the other entity.
This is my controller:
public function searchtabflightResultAction(Request $request)
{
$form = $this->createForm(new SearchflightType());
if ($this->get('request')->getMethod() == 'POST')
{
$form->handleRequest($request);
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('FLYBookingsBundle:Post')->searchflight($form['airport']->getData());
} else {
throw $this->createNotFoundException('The page you were looking for doesn\'t exist.');
}
return $this->render('FLYBookingsBundle:Post:searchtabflightResult.html.twig', array('entities' => $entities));
}
PostRepository.php
public function searchflight($entity)
{
$qb = $this->createQueryBuilder('u')
->select('u')
->where('u.airport like :entity')
->andWhere('u.airport1 like :entity')
->orderBy('u.id')
->setParameter('entity', '%'.$entity.'%');
return $qb->getQuery()->getResult();
}
Try something like :
In your controller:
$entities = $em->getRepository('FLYBookingsBundle:Post')->searchflight($form);
In your repo:
public function searchflight(FormInterface $form)
{
$qb = $this->createQueryBuilder('u');
if ($form->has('airport')) {
$qb->andWhere(
$qb->expr()->like('u.airport', ':airport')
)
->setParameter('airport', '%'. $form->get('airport')->getData().'%')
}
// ... complete like this with the other params
Probably it's an easy answer, but I don't find it!
I'm using Eloquent to perform my queries into the database, having this code:
public function postSearch(Request $request)
{
$query = Customer::select('identification', 'first_name', 'second_name', 'first_lastname', 'second_lastname', 'genre')
->where('identification', 'LIKE', "%$request->identification%")
->where('first_name', 'LIKE', "%$request->first_name%")
->Where('second_name', 'LIKE', "%$request->second_name%")
->Where('first_lastname', 'LIKE', "%$request->first_lastname%")
->Where('second_lastname', 'LIKE', "%$request->second_lastname%")
->Where('genre', 'LIKE', "%$request->genre%");
$request->session()->put('list', $query->get());
$customers = $query->paginate(20);
return view('customer.index', compact('customers'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$query = Customer::select('identification', 'first_name', 'second_name', 'first_lastname', 'second_lastname', 'genre');
$request->session()->put('list', $query->get());
$customers = $query->paginate(20);
return view('customer.index', compact('customers'));
}
It works perfectly, but now, I want to optimize it creating another funtion which receives the $query. Something like this:
public function displayResult(Builder $query,Request $request)
{
$request->session()->put('list', $query->get());
$customers = $query->paginate(20);
return view('customer.index', compact('customers'));
}
The objective is to call the function from my previous methods, e.g:
public function index(Request $request)
{
$query = Customer::select('identification', 'first_name', 'second_name', 'first_lastname', 'second_lastname', 'genre');
$this->displayResult($query, $request);
}
But, my view is not displaying nothing. Am I doing something wrong?
Should I use a Model instead Builder parameter? If I do so, then it's displaying this error:
Argument 1 passed to
App\Http\Controllers\CustomerController::displayResult() must be an
instance of App\Http\Controllers\Model, instance of
Illuminate\Database\Eloquent\Builder given, called in ....on line 54 and defined
That line is exactly where I call to my new funtion.
Thanks in advance.
Your displayResult() method returns the view instance, but you forgot to return it from your controller's index() method.
Replace
$this->displayResult($query, $request);
with
return $this->displayResult($query, $request);
I have this code:
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$entities = $em
->getRepository('BreedrGeckoBundle:Weight')
->findBy(array('user' => $user), array());
return array(
'entities' => $entities,
);
}
Which is fine, gets all the weights in the database for the current user.
But how can I order the results so that all the weight entries for the same gecko id are together?
My table structure is as follows:
You need to query for your objects using Doctrine's QueryBuilder.
Something like this:
$repository = $this->getDoctrine()
->getRepository('BreedrGeckoBundle:Weight');
$query = $repository->createQueryBuilder('w')
->where('w.user = :user')
->orderBy('w.geckoId ASC')
->getQuery();
$query->setParameter(':user', $user);
$entities = $query->getResult();
If you want additional ordering, you can do something like:
->orderBy('w.geckoId ASC, w.weight ASC, w.id ASC')
You should create your own repository and use the addGroupBy function on the querybuilder. Example:
class WeightRepository extends EntityRepository
{
public function getGroupedByGeckoId(User $user)
{
$qb = $this->createQueryBuilder('weight');
$qb->select('whateverYouWant');
$qb->andWhere('weight.user = :user');
$qb->setParameter('user', $user);
$qb->addGroupBy('weight.geckoId');
return $qb->getQuery()->getResult();
}
}
You can also order by using the repository object itself like so:
public function indexAction()
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$entities = $em
->getRepository('BreedrGeckoBundle:Weight')
->findBy(array('user' => $user), array('geckoId' => 'ASC'));
return array(
'entities' => $entities,
);
}