Can't paginate in livewire component - laravel

I'm trying to paginate items in a livewire component, I have this query
protected $listeners = [
'franchises:coords' => 'getFranchises'
];
public $franchiseList;
public function render()
{
return view('livewire.franchise-list', ['franchiseList' => $this->franchiseList]);
}
public function getFranchises($coords)
{
if ($coords) {
$latitude = json_decode($coords)[0];
$longitude = json_decode($coords)[1];
$radiusInMeters = 800;
$this->franchiseList = Franchise::select(DB::raw('*, ( 6371000 * acos( cos( radians(' . $latitude . ') )
* cos( radians( latitude ) ) * cos( radians( longitude ) - radians(' . $longitude . ') )
+ sin( radians(' . $latitude . ') ) * sin( radians( latitude ) ) ) ) AS distance'))
->having('distance', '<', $radiusInMeters)
->orderBy('distance')
->paginate(8);
}
}
the component is included in my "maps.blade"
<div class="lg:basis-1/4 md:basis-1/4 sm:px-6 lg:px-8">
<livewire:franchise-list/>
</div>
and in my blade view, I have this
#if(!empty($franchiseList))
{{$franchiseList->links()}}
#endif
but I get this error
Livewire component's [franchise-list] public property [franchiseList]
must be of type: [numeric, string, array, null, or boolean]. Only
protected or private properties can be set as other types because
JavaScript doesn't need to access them.
If I try to change pagination by adding these lines to the getFranchises function and adding $links to public
public $franchiseList, $links;
//after paginate
$this->links = $this->franchiseList;
$this->franchiseList = collect($this->franchiseList->items);
and in the blade change to this
#if(!empty($franchiseList) && $links->links())
{{$links->links()}}
#endif
I get this error
Error Cannot access protected property
Illuminate\Pagination\LengthAwarePaginator::$items
How can I paginate in livewire? where is the problem?

Ok, as I guess your issue is right there in render method. Instead of doing what you're doing, change this once you have in the mount the property initialized
public $franchiseList;
public function mount()
{
$this->franchiseList = [];
}
public function render()
{
return view('livewire.franchise-list');
}
So, as the property is public you can bind it in blade directly. At load component, it is an empty array and on event (in listener) this will change to passed value. That's the idea, but if you do this ['franchiseList' => $this->franchiseList] it's going to be crashed (when same name). I can't tell you why because I really don't know the answer but I know this happens from my experience.

Related

How can I add AJAX filters to an existing AJAX load more

I have a fully working AJAX load more button on my Wordpress posts. On click, it loads the next page of posts and appends them directly to the end of the first set.
I now need to create category filters. So when a user clicks a category name, it updates the results below via AJAX to only show posts in that category - BUT I need the load more ajax to continue to work correctly. I've tried hashing together two different AJAX calls, and also tried combining both AJAX into one, but I can't seem to get them talking...
Here's the code:
functions.php
function we_title_filters() {
if(is_home()): ?>
<div class="title-filters">
<h3 class="widget-title" style="display:inline-block;">Latest News</h3>
<div class="filters">
<?php
$include = array(3651, 7, 2828, 2829, 2172);
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0,
'include' => $include
) );
foreach ( $categories as $category ) {
printf( '%2$s',
esc_url( get_category_link( $category->term_id ) ),
esc_html( $category->name )
);
}
?>
<div class="dropdown" style="float:right;">
<span class="dropbtn">More</span>
<ul class="more-list">
<?php
$include = array(3651, 7, 2828, 2829, 2172);
$categories = get_categories( array(
'orderby' => 'name',
'parent' => 0,
'include' => $include
) );
foreach ( $categories as $category ) {
printf( '<li>%2$s</li>',
esc_url( get_category_link( $category->term_id ) ),
esc_html( $category->name )
);
}
?>
</ul>
</div>
</div>
</div>
<?php endif;
}
This outputs the filters in a list. On click of one of them, it needs to AJAX change the results, but also keep the load more button working, within that category
/* AJAX load more stuff */
/**
*
* Infinite Scroll
*
* #since 1.0.0
*
* #author Lauren Gray
* #author Bill Erickson
* #link http://www.billerickson.net/infinite-scroll-in-wordpress
*
* Enqueue necessary JS file and localize.
*
*/
add_action( 'wp_enqueue_scripts', 'sn_infinite_scroll_enqueue' );
function sn_infinite_scroll_enqueue() {
if ( ! is_singular() ) {
global $wp_query;
$args = array(
'nonce' => wp_create_nonce( 'be-load-more-nonce' ),
'url' => admin_url( 'admin-ajax.php' ),
'query' => $wp_query->query,
'maxpage' => $wp_query->max_num_pages,
);
wp_enqueue_script( 'sn-load-more', get_stylesheet_directory_uri() . '/js/load-more.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'sn-load-more', 'beloadmore', $args );
}
}
/**
*
* Infinite Scroll
*
* #since 1.0.0
*
* #author Lauren Gray
* #author Bill Erickson
* #link http://www.billerickson.net/infinite-scroll-in-wordpress
*
* Parse information
*
*/
add_action( 'wp_ajax_sn_infinite_scroll_ajax', 'sn_infinite_scroll_ajax' );
add_action( 'wp_ajax_nopriv_sn_infinite_scroll_ajax', 'sn_infinite_scroll_ajax' );
function sn_infinite_scroll_ajax() {
if ( ! is_singular() ) {
check_ajax_referer( 'be-load-more-nonce', 'nonce' );
$excluded_ids = get_field('top_stories', option);
$args = isset( $_POST['query'] ) ? array_map( 'esc_attr', $_POST['query'] ) : array();
$args['post_type'] = isset( $args['post_type'] ) ? esc_attr( $args['post_type'] ) : 'post';
$args['paged'] = esc_attr( $_POST['page'] );
$args['post_status'] = 'publish';
$args['post__not_in'] = $excluded_ids;
$pageType = esc_attr( $_POST['pageType'] );
if ( $pageType == "is-home" ) {
$initial = 30;
$ppp = 30;
$columns = 3;
}
else {
$initial = 30;
$ppp = 30;
$columns = 3;
}
$args['posts_per_page'] = $ppp;
$args['offset'] = $initial + ( $ppp * ( $_POST['page'] ) );
ob_start();
$loop = new WP_Query( $args );
if( $loop->have_posts() ): while( $loop->have_posts() ): $loop->the_post();
sn_post_summary( $loop->current_post, $columns );
endwhile;
endif;
wp_reset_postdata();
$page = esc_attr( $_POST['page'] );
}
$data = ob_get_clean();
wp_send_json_success( $data );
wp_die();
}
}
/**
*
* Infinite Scroll
*
* #since 1.0.0
*
* #author Lauren Gray
* #author Bill Erickson
* #link http://www.billerickson.net/infinite-scroll-in-wordpress
*
* Output articles
*
*/
function sn_post_summary( $count, $columns ) {
// Be able to convert the number of columns to the class name in Genesis
$fractions = array( '', 'half', 'third', 'fourth', 'fifth', 'sixth' );
// Make a note of which column we're in
$column_number = ( $count % $columns ) + 1;
// Add one-* class to make it correct width
$countClasses = sprintf( 'one-' . $fractions[$columns - 1] . ' ', $columns );
// Add a class to the first column, so we're sure of starting a new row with no padding-left
if ( 1 == $column_number )
$countClasses .= 'first ';
remove_action( 'genesis_entry_content', 'genesis_do_post_content' );
remove_action( 'genesis_entry_header', 'genesis_post_info', 12 );
remove_action( 'genesis_entry_content', 'genesis_do_post_image', 8 );
add_action( 'genesis_entry_header', 'genesis_do_post_image', 8 );
echo '<article class="' . $countClasses . implode( ' ', get_post_class() ) . '">'; // add column class
do_action( 'genesis_entry_header' );
echo '</article>';
}
This is a modified version of the infinite scroll loader found here: https://gist.github.com/graylaurenm/86daa4f23aa8749c0933f72133ac7106
I removed the infinite scroll options so it only loads on click of the button.

Identify the generated URL path

I've this github package for my Laravel application, using composer, which creates sitemaps, but I am not able to understand where those sitemaps are rendered.
I had luck in finding the main sitemap after hitting /sitemap.xml URL location of my website, but I am unable to find other sitemaps like Google News sitemap one, which is supported by the package.
The responsible function seems this one, but my coding skills restrict me from understanding the rendered path:
/**
* Returns document with all sitemap items from $items array
*
* #param string $format (options: xml, html, txt, ror-rss, ror-rdf, google-news)
* #param string $style (path to custom xls style like '/styles/xsl/xml-sitemap.xsl')
*
* #return View
*/
public function render($format = 'xml', $style = null)
{
// limit size of sitemap
if ($this->model->getMaxSize() > 0 && count($this->model->getItems()) > $this->model->getMaxSize())
{
$this->model->limitSize($this->model->getMaxSize());
}
else if ('google-news' == $format && count($this->model->getItems()) > 1000)
{
$this->model->limitSize(1000);
}
else if ('google-news' != $format && count($this->model->getItems()) > 50000)
{
$this->model->limitSize();
}
$data = $this->generate($format, $style);
if ('html' == $format)
{
return $data['content'];
}
return $this->response->make($data['content'], 200, $data['headers']);
}
Im generating my sitemap on HomeController, with this function:
public function sitemap()
{
$settings_general = Utils::getSettings("general");
if ($settings_general->generate_sitemap == 1) {
// create new sitemap object
$sitemap = App::make("sitemap");
// get all posts from db
$posts = DB::table('posts')->orderBy('created_at', 'desc')->limit(600)->get();
// add every post to the sitemap
foreach ($posts as $post) {
$sitemap->add(URL::to('/') . "/" . $post->slug, $post->updated_at, '1', 'hourly', null, $post->title);
}
$pages = DB::table('pages')->orderBy('created_at', 'desc')->get();
// add every page to the sitemap
foreach ($pages as $page) {
$sitemap->add(URL::to('/') . "/" . $page->slug, $page->updated_at, '1', 'hourly', null, $page->title);
}
$categories = DB::table('categories')->orderBy('created_at', 'desc')->get();
// add every category to the sitemap
foreach ($categories as $category) {
$sub_categories = SubCategories::where('parent_id', $category->id)->get();
$sitemap->add(URL::to('/') . "/category/" . $category->slug, $category->updated_at, '1', 'hourly', null, $category->title);
foreach ($sub_categories as $sub_category) {
$sitemap->add(URL::to('/') . "/category/" . $category->slug . "/" . $sub_category->slug, $category->updated_at, '1', 'hourly', null, $category->title);
}
}
return $sitemap->render('xml');
}
}

Can't get POST data with AJAX

I would like to show 4 objects in a page, with a "load more" button which show 4 more object each time we click.
I try to adapt a PHP script which works(tested) to Symfony.
The problem is that I can't get the POST data (a page number) in my Symfony function, even if I can see it in the chrome developer toolbar...
My controller:
<?php
/**
* Content controller.
*
* #Route("content")
*/
class ContentController extends Controller
{
/**
* Lists all software.
*
* #Route("/software", name="content_software")
* #Method({"POST", "GET"})
*/
public function softwareAction(Request $request)
{
if ($request->request->get('page')){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT,
FILTER_FLAG_STRIP_HIGH);
$item_per_page = 4;
$position = (($page_number-1) * $item_per_page);
$contents = $this->getRepo()->findBy(array(),null,$item_per_page,$position);
}
else
{
$contents = "didn't work";
}
return $this->render('content/index.html.twig', array(
'contents' => $contents
));
}
}
index.html.twig :
{% extends 'loicCoreBundle::Default/layout.html.twig' %}
{% block body %}
{{ dump(contents) }}
<script type="text/javascript">
var track_page = 1; //track user click as page number, right now page number is 1
load_contents(track_page); //load content
$("#load_more_button").click(function (e) { //user clicks on button
track_page++; //page number increment everytime user clicks load button
load_contents(track_page); //load content
});
//Ajax load function
function load_contents(track_page){
$.post( "{{ path('content_software') }}", {'page': track_page}, function(data){
if(data.trim().length == 0){
//display text and disable load button if nothing to load
$("#load_more_button").text("No more records!").prop("disabled", true);
}
});
}
</script>
{% endblock %}
I'm not sure where your errors are coming from, I've done a similar test which just works (no problems with $request->request->get()).
You are however loading a full template (index.html) for each sub request as well. Usually you want to separate calls like this into api like methods, however for simple things its a bit silly.
Here is an expanded/ updated version of what I tested, I avoided post data all together and just used the method as switch. This worked fine so try and figure out where you went wrong using this as reflection (or whatever you like to do with it). Note this uses a simple PHP range array for test data, not entities but it should remain the same principle.
Controller
/**
* #Route(
* "software/{page}/{limit}",
* name="content_software",
* requirements = {
* "page": "[1-9]\d*",
* "limit": "[1-9]\d*"
* }
* )
*/
public function softwareAction(Request $request, $page = 1, $limit = 4) {
if ($request->isMethod('POST')) {
// replace these two lines with database logic (SELECT & LIMIT)
$start = ($page - 1) * $limit;
$items = array_slice(range(1, 10), $start, $limit); // Just using a simple item array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] as test data
$content = '';
foreach ($items as $item) {
$content .= $this->get('twig')->render('someItemTemplate.html.twig', ['item' => $item]);
}
return new Response($content);
} else {
// alternatively you can send out the default items here for the first get request
// and use the same item template above with {% embed %} to render them in this template
return $this->render('someTemplate.html.twig');
}
}
someTemplate.html.twig
<html>
<head>
<title>Cake or death?</title>
</head>
<body>
<ul id="put-the-things-here"></ul>
<button id="next_please">Ehh cake please!</button>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
var pageTracker = 1,
$next = $("#next_please"),
$target = $('#put-the-things-here');
load_contents(pageTracker);
$next.click(function (e) {
load_contents(++pageTracker);
});
function load_contents(page) {
// using post just for the request method (page is in the url)
$.post("{{ path('content_software') }}/" + page,
function (data) {
if (data) {
$target.append(data);
} else {
$target.append('<li>We are out of cake.</li>');
$next.attr('disabled', true);
}
}
);
}
</script>
</body>
</html>
someItemTemplate.twig
<li>Cake: {{ item }}</li>
try this:
$request->request->get('page')
Instead of this:
$request->request->has('page')
If it doesn't work try to:
var_dump($request->request->all());
And check the variables
I think too the problem comes from routes.
Error message when I use only "POST" method :
"No route found for "GET /content/software": Method Not Allowed (Allow: POST, DELETE)".
Because when I arrive on my page by clicking a link , I arrive with a GET method.
However, when I click on my "load more" button the AJAX works and I can see in my symfony debugbar that I get POST variable:
The problem is when I first arrive on my page I think.
#Jenne van der Meer: Thank you but I would like not to use GET parameters.
I add my full controller code, in case of:
/**
* Content controller.
*
* #Route("content")
*/
class ContentController extends Controller
{
public function getRepo(){
$em = $this->getDoctrine()->getManager();
$repo = $em->getRepository('loicContentBundle:Content');
return $repo;
}
// private $theRepo = getDoctrine()->getManager()->getRepository('loicContentBundle:Content');
/**
* Lists all content entities.
*
* #Route("/", name="content_index")
* #Method("GET") */
public function indexAction(Request $request)
{
$contents = $this->getRepo()->findAll();
$this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');
$formFilter = $this->createFormBuilder()
->add('_', EntityType::class,array(
'class' => 'loicFilterBundle:Filter',
'multiple' => true,
'expanded' => true,
'choice_label' => function($value) {
return ($value->getName());
},
))
->add('Appliquer filtres', SubmitType::class)
->getForm();
$formFilter->handleRequest($request);
$data = '';
if ($formFilter->isSubmitted() && $formFilter->isValid()) {
$data = $formFilter->getData();
$data = $data['_']->toArray();
$contents = $this->getRepo()->findAll();
}
else
{$contents = $this->getRepo()->findAll();
}
return $this->render('content/index.html.twig', array(
'contents' => $contents,'formFilter' => $formFilter->createView(),'request' => $request
));
}
public function contentAction($categoryId)
{
$contents= $this->getRepo()->findBy(
array('contentCategorycontentCategory' => $categoryId),
null,
4
);
return $contents;
}
/**
* Lists all software.
*
* #Route("/software", name="content_software")
*/
public function softwareAction(Request $request)
{
var_dump($request->request->all());
$bla = $request->request->get('page');
if ($request->request->get('page')){
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT,
FILTER_FLAG_STRIP_HIGH);
$item_per_page = 4;
$position = (($page_number-1) * $item_per_page);
$contents = $this->getRepo()->findBy(array(),null,$item_per_page,$position);
}
else
{
$contents = "didn't work";
}
return $this->render('content/index.html.twig', array(
'contents' => $contents,'bla' => $bla
));
}
/**
* Lists all videos.
*
* #Route("/videos", name="content_videos")
* #Method("GET")
*/
public function videoAction()
{
$contents = $this->contentAction(5);
return $this->render('content/index.html.twig', array(
'contents' => $contents,
));
}
/**
* Lists all testimonies.
*
* #Route("/testimonies", name="content_testimonies")
* #Method("GET")
*/
public function testimoniesAction()
{
$contents = $this->contentAction(8);
return $this->render('content/index.html.twig', array(
'contents' => $contents,
));
}
/**
* Lists all whiteBooks.
*
* #Route("/whiteBooks", name="content_whiteBooks")
* #Method("GET")
*/
public function whiteBooksAction()
{
$contents = $this->contentAction(3);
return $this->render('content/index.html.twig', array(
'contents' => $contents,
));
}
/**
* Lists all actuality.
*
* #Route("/actuality", name="content_actuality")
* #Method("GET")
*/
public function actualityAction()
{
$contents = $this->contentAction(6);
return $this->render('content/index.html.twig', array(
'contents' => $contents,
));
}
/**
* Lists all webinar.
*
* #Route("/webinar", name="content_webinar")
* #Method("GET")
*/
public function webinarAction()
{
$contents = $this->contentAction(4);
return $this->render('content/index.html.twig', array(
'contents' => $contents,
));
}
/**
* Lists all blog posts.
*
* #Route("/blog", name="content_blog")
* #Method("GET")
*/
public function blogAction()
{
$contents = $this->contentAction(7);
return $this->render('content/index.html.twig', array(
'contents' => $contents,
));
}
/**
* Creates a new content entity.
*
* #Route("/new", name="content_new")
* #Method({"GET", "POST"})
*/
public function newAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$content = new Content();
$form = $this->createForm('loic\ContentBundle\Form\ContentType', $content);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($content);
$em->flush($content);
return $this->redirectToRoute('content_show', array('id' => $content->getIdcontent()));
}
return $this->render('content/new.html.twig', array(
'content' => $content,
'form' => $form->createView(),
));
}
/**
* Displays a form to edit an existing content entity.
*
* #Route("/{id}/edit", name="content_edit")
* #Method({"GET", "POST"})
*/
public function editAction(Request $request, Content $content)
{
$deleteForm = $this->createDeleteForm($content);
$editForm = $this->createForm('loic\ContentBundle\Form\ContentType', $content);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('content_edit', array('id' => $content->getIdcontent()));
}
return $this->render('content/edit.html.twig', array(
'content' => $content,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Deletes a content entity.
*
* #Route("/{id}", name="content_delete")
* #Method("DELETE")
*/
public function deleteAction(Request $request, Content $content)
{
$form = $this->createDeleteForm($content);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($content);
$em->flush();
}
return $this->redirectToRoute('content_index');
}
/**
* Creates a form to delete a content entity.
*
* #param Content $content The content entity
*
* #return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Content $content)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('content_delete', array('id' => $content->getIdcontent())))
->setMethod('DELETE')
->getForm()
;
}
}
My Bundle/Resources/config/routing.yml file is empty.

sorting data error codeigniter

I have some problems with sorting datas when i try type distance for example to 5 i have this error:
Unknown column 'dystans' in 'having clause'
SELECT COUNT(*) AS `numrows` FROM `meet` JOIN `category` ON `category`.`id` = `meet`.`category_id` HAVING `dystans` <= '5' ORDER BY `when` ASC
Filename: C:/xamppNew/htdocs/dzielimypasje/application/controllers/Meetings.php
Line Number: 177
Im using codeigniter. Line 177 is this
$data['count'] = $count = $this->db->count_all_results();
My controller:
$lat = $this->session->userdata('lat');
$lng = $this->session->userdata('lng');
// To pagination
$this->load->library('pagination');
$limit = 10;
$offset = $this->uri->segment(4);
$this->db->start_cache();
$this->db->select('*, meet.id,
(6731 * acos( cos( radians( '.$lat.')) * cos( radians( meet.lat)) *
cos( radians( meet.lng) - radians( '.$lng.')) + sin( radians( '.$lat.')) *
sin( radians( meet.lat)))) AS dystans');
//data from search engine
$level = $this->input->post('level');
$cat = $this->input->post('category');
$dystans = $this->input->post('dystans');
$when = $this->input->post('when');
if ($level) {
$this->db->where('level', $level);
}
if ($cat) {
$this->db->where('category_id', $cat);
}
if ($when) {
$this->db->where('when <=', $when);
}
if ($dystans) {
$this->db->having('dystans <=', $dystans);
}
$this->db->order_by('when', 'ASC');
$this->db->from('meet');
$this->db->join('category', 'category.id = meet.category_id');
$this->db->stop_cache();
// count for pagination
$data['count'] = $count = $this->db->count_all_results();
// to pagination
$this->db->limit($limit, $offset);
$data['meetings'] = $this->db->get();
$this->db->flush_cache();
$config = some config for pagination ...
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->view( 'site/meetings/index' , $data );
view:
<select type="text" name="dystans" placeholder="distance">
<option value="">Odległość</option>
<option value="1">Do 1 km</option>
<option value="2">Do 2km</option>
<option value="5">Do 5km</option>
<option value="10">Do 10km</option>
</select>
Any idea how to solve this ?? Propably its something with cache but im not sure, im new in this.
Alright. I dug into this and fixed everything I could find. I ditched active record for straight database access with query() function because...well...I have never liked active record and personally believe it is much much cleaner to write your query in an admin tool and copy it into your model. This gives you access to ALL of mysql's capabilities without having to jump through hoops (not to mention if you wind up using a different code base in the future you already have your queries and don't have to dig back through all of the active record code).
The main reason you were breaking at the dystans block was because you were trying to use a dynamically generated column within your where clause. The where clause only knows about columns that exist within the tables you have joined on. So to do what you are needing you have to run back through your formula.
I have also broken this out so that all of the filters will work in conjunction with one another. A user can now use filter when with filter dystans and the query will be build accordingly.
I haven't tested this code because obviously I do not have your database but it is the same way I code all of my applications. If you have trouble please let me know.
Also you should really consider breaking out your business logic or at least database interaction into a codeigniter model. Controllers should only ever act as a router between your models and views.
The link to my post on codeigniter pagination
<?php
$lat = $this->session->userdata('lat');
$lng = $this->session->userdata('lng');
// To pagination
$this->load->library('pagination');
$limit = 10;
$offset = (isset($this->uri->segment(4)) && is_numeric($this->uri->segment(4))) ? $this->uri->segment(4) : 0;
$bindArray = array();
$query = "SELECT *,"
. " (6731 * acos(cos( radians(?)) * cos( radians( meet.lat))"
. " * cos( radians( meet.lng) - radians(?)) + sin( radians(?))"
. " * sin( radians( meet.lat)))) AS dystans";
$bindArray[] = $lat;
$bindArray[] = $lng;
$bindArray[] = $lat;
$query .= " FROM meet JOIN category ON category.id = meet.category_id"
. " WHERE TRUE = TRUE";
//data from search engine
$level = $this->input->post('level');
$cat = $this->input->post('category');
$dystans = $this->input->post('dystans');
$when = $this->input->post('when');
if($level){
$query .= " AND meet.level = ?";
$bindArray[] = $level;
}
if($cat){
$query .= " AND meet.category_id = ?";
$bindArray[] = $cat;
}
if($when){
$query .= " AND meet.when <= ?";
$bindArray[] = $when;
}
if($dystans){
$query .= " AND (6731 * acos(cos( radians(?)) * cos( radians( meet.lat))"
. " * cos( radians( meet.lng) - radians(?)) + sin( radians(?))"
. " * sin( radians( meet.lat)))) <= ?";
$bindArray[] = $dystans;
}
$query .= "LIMIT ?,?";
$bindArray[] = $offset;
$bindArray[] = $limit;
$query_result = $this->db->query($query, $bindArray);
$data['count'] = $query_result->num_rows();
$data['meetings'] = $query_result->result();
$config = 'YOUR PAGINATION CONFIGURATION';
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
$this->load->view( 'site/meetings/index' , $data );

LARAVEL: trying to get a property from a non-object

I am progressively solving (always with your help) this Eloquent query but have not managed to completely solve it. Sorry to still staying at it, but I am struggling to my best.
I have written the query in two flavors. I would like to keep the Laravel one since I am using that but it is that one the one which doesn't work:
WORKS WHEN I DO IT ON PHPMYADMIN SQL WINDOW:
select properties.id, title, city, price, postedat, propertytype,
( 3959 * acos( cos( radians(43) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-1.5) ) + sin( radians(43) ) * sin( radians( lat ) ) ) ) AS distance
from properties
join addresses
on properties.id_address_fk = addresses.id
where city = 'Biarritz'
HAVING distance < 100
ORDER BY distance
LIMIT 0, 20;
BELOW DOESN'T WORK (I get a: trying to get property from a non-object error)
$properties = DB::table('properties')
->join('addresses', 'properties.id_address_fk', '=', 'addresses.id')
->select('properties.id', 'title', 'city', 'price', 'postedat', 'propertytype',
DB::raw('3959 * acos( cos( radians(43) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians (-1.5) )+ sin( radians(43) ) * sin( radians( lat ) ) ) as distance') );
if (!empty($location)) {
$properties = $properties->where('location', '=', $location);
}
if (!empty($propertytype)) {
$properties = $properties->where('propertytype', '=', $propertytype);
}
if (!empty($bedrooms)) {
$properties = $properties->where('bedrooms', '>=', $bedrooms);
}
if (!empty($transaction)) {
$properties = $properties->where('transaction', '=', $transaction);
}
if (!empty($minprice)) {
$properties = $properties->where('price', '>=', $minprice);
}
if (!empty($maxprice)) {
$properties = $properties->where('price', '<=', $maxprice);
}
$properties->having('distance', '<', 100)
->orderBy('distance', 'desc')
->skip(0)
->take(5)
->get();
return View::make('propertyfound', compact('premium', 'properties'));
UPDATE:
Of course, the errors are when it tries to get property from a non-object
#foreach($properties as $propfound)
<div class="row premium">
<div class="col-sm-3 col-xs-3">
<a href="{{URL::route('property', array($propfound->id) )}}" class="thumbnail " >{{ HTML::image("public/css/images/houses/$propfound->houses1")}}</a>
<h5>Guide price: £ {{$propfound->price}}</h5>
<h6>Bedrooms: {{$propfound->bedrooms}}</h6>
<h6>Days on site: 4</h6>
<h6>Sqft: {{$propfound->m2}}</h6>
</div>
<div class="col-sm-9">
<h3>{{$propfound->title}}</h3>
<p>{{$propfound->description}}</p>
<p class="hidden-xs">More details, 14 photos, floorplan and brochure | Save property | Contact agent | Upgrade listing</p>
<p class="hidden-xs">Marketed by Knight Frank, Richmond. Telephone: 0843 314 8224 BT 4p/min </p>
</div>
</div>
<hr />
#endforeach
You can't simply chain ->get() to the original DB object and get results.
// Doesn't work
$object->having()->take()->get();
foreach ( $object as $value ) {
// $value is some part of the query builder/eloquent object
}
You have to assign to a new variable
// Works
$results = $object->having()->take()->get();
foreach ( $results as $value ) {
// $value is db result
}

Resources