How can I use pagination with vuejs and laravel
I first used this in order to have my posts with users,categories and photo.
public function index()
{
//
$posts = Post::with('user', 'category', 'photo')->orderBy('id', 'desc')->get();
return response()->json([
'posts' => $posts,
], 200);
}
All works, but now I want to add pagination and for some reason it does not work. I did like this:
$posts = Post::with('user', 'category', 'photo')->orderBy('id', 'desc')->paginate(5)->get();
How can I make my pagination work?
I believe you just need to take out the get() from the end:
$posts = Post::with('user', 'category', 'photo')->orderBy('id', 'desc')->paginate(5);
When I use paginate I skip the get().
The paginate method looks for a page query string argument on the HTTP Request. It probably doesn't work if it's not present. You seem to be creating a route meant for an API. If that's the case, it's quite likely you don't have the page variable set in your HTTP request. You can check the presence of this variable or create your own paginator: https://laravel.com/docs/5.6/pagination#manually-creating-a-paginator
Related
I'm trying to make a filtering component for my website and I want to be able to get that data which they specified through the filter from the MongoDB database. I'm using MERN stack and want to conditionally send a query to the database to retrieve based on whether or not it's empty or not. If it's empty, it means the user wants anything in that specific category and not one specific thing so I don't want to send an empty query to the DB which is just going to look for an empty string/array and realize that nothing in the DB has an empty string/array and won't return anything.
That's why I want to conditionally render my query parameter because that's the only workaround I can think of for my earlier question which does not have a solution for:
How can I send an object as a query and use the $all operator in MERN stack?
Here is the code and where I want the the conditional render to happen:
var t = ["People"]
const test = await Project.find( {$all: {
theme: t // have something that condditionally sends this, if t is empty then don't send it
}}
).sort({ createdAt: -1 })
console.log(test)
You can conditionally construct the search-filter:
const filter = {};
if (t.length) { // or whatever condition you need
filter.$all = {theme: t};
}
const test = await Project.find(filter) // rest of your code
I am integrating the hubspot API to track user interaction with our site. I am creating dynamic lists and I want to filter a user into a certain contact list by which URL they visit.
"filters": [
[
{
"operator": "CONTAINS",
"property": "hs_URL",
"value": `${id}`
},
],
]
I keep getting this error for all my attempts:
{"status":"error","message":"Couldn't find a Property with the given name 'hs_URL'","correlationId":"0723dcee-534b-4f92-9104-509d6885abbe","propertiesErrorCode":"PROPERTY_NOT_FOUND"},
I cannot seem to find a master property list and have tried many string combinations. Anyone familiar with hubspot property lists would be my savior.
Thank you~!
It's been a few months, so you may not need this anymore, but since I landed here while looking for a way to get all the properties from an object type in hubspot using nodejs, this might help others looking for the solution.
The master list of properties can be retrieved with the following API call:
const response = await hubspotClient.crm.properties.coreApi.getAll(objectType, false);
The arguments for getAll() expect:
objectType: a string, i.e "contacts".
archived: a boolean, i.e false. Set this true if you want to get archived properties.
The following code was adapted based on this page from the hubspot API docs:
https://developers.hubspot.com/docs/api/crm/properties
Once you're on the page, you can click on the "Endpoints" Tab to reveal code snippets for multiple environments, including nodejs.
For this example, getProperties(), retrieves all properties for a given object type. I used contacts for the object type, which I believe is where you are storing the url property, but you could use the same function to get properties for other object types such as companies or deals.
It might be worth noting that I mapped the results to return just the property names, which sounds like all you need for your case, but more information is contained in the results if you need it. Just remove this bit to get more information on each property:
.map(prop => prop.name)
const hubspot = require('#hubspot/api-client')
const hubspotClient = new hubspot.Client({ apiKey: "YOUR_API_KEY" })
const getProperties = async (objectType) => {
try {
const response = await hubspotClient.crm.properties.coreApi.getAll(objectType, false);
return response.body.results.map(prop => prop.name);
} catch (e) {
e.message === 'HTTP request failed'
? console.error(JSON.stringify(e.response, null, 2))
: console.error(e);
}
}
Here's an example for running the function to get a list of all property names for contacts.
(async () => {
var properties = await getProperties("contacts");
console.log(JSON.stringify(properties ,null,2));
})();
It took me a bit to find this, so figured I would post here in the hopes it saves time for someone else. This is the first time I've posted a solution, and I'm pretty new to this API and Hubspot in general, so feedback and/or better solutions are welcome. Cheers.
In Mongoose, I can use a query populate to populate additional fields after a query. I can also populate multiple paths, such as
Person.find({})
.populate('books movie', 'title pages director')
.exec()
However, this would generate a lookup on book gathering the fields for title, pages and director - and also a lookup on movie gathering the fields for title, pages and director as well. What I want is to get title and pages from books only, and director from movie. I could do something like this:
Person.find({})
.populate('books', 'title pages')
.populate('movie', 'director')
.exec()
which gives me the expected result and queries.
But is there any way to have the behavior of the second snippet using a similar "single line" syntax like the first snippet? The reason for that, is that I want to programmatically determine the arguments for the populate function and feed it in. I cannot do that for multiple populate calls.
After looking into the sourcecode of mongoose, I solved this with:
var populateQuery = [{path:'books', select:'title pages'}, {path:'movie', select:'director'}];
Person.find({})
.populate(populateQuery)
.execPopulate()
you can also do something like below:
{path:'user',select:['key1','key2']}
You achieve that by simply passing object or array of objects to populate() method.
const query = [
{
path:'books',
select:'title pages'
},
{
path:'movie',
select:'director'
}
];
const result = await Person.find().populate(query).lean();
Consider that lean() method is optional, it just returns raw json rather than mongoose object and makes code execution a little bit faster! Don't forget to make your function (callback) async!
This is how it's done based on the Mongoose JS documentation http://mongoosejs.com/docs/populate.html
Let's say you have a BookCollection schema which contains users and books
In order to perform a query and get all the BookCollections with its related users and books you would do this
models.BookCollection
.find({})
.populate('user')
.populate('books')
.lean()
.exec(function (err, bookcollection) {
if (err) return console.error(err);
try {
mongoose.connection.close();
res.render('viewbookcollection', { content: bookcollection});
} catch (e) {
console.log("errror getting bookcollection"+e);
}
//Your Schema must include path
let createdData =Person.create(dataYouWant)
await createdData.populate([{path:'books', select:'title pages'},{path:'movie', select:'director'}])
Is there way to build complete object for mongoose to use as query? When making route for search I need to pass many query parameters and sanitize them in express middleware. From those I would like to build query object.
I ended up with something like this:
Inside midleware:
res.locals.filter = {
query: ...,
projection: ...,
sort: ...,
limit: ....,
}
inside router:
User.find(res.locals.filter.query)
.sort(res.locals.filter.sort)
.limit(res.locals.filter.limit)
.exec()
Is there any way to format my filter so I can pass it all at once? Found some examples but nothing seem to work for me...
In other word do something like:
User.query(filter)
You can do this by adding query as a static method on your schema:
userSchema.statics.query = function(filter) {
return this.find(filter.query).sort(filter.sort).limit(filter.limit);
};
Which you could then call as:
User.query(res.locals.filter).exec(callback);
As it was pointed out by JohnnyHK, the style of find call with object fields like $query and $orderBy was only supported in the shell (and is now deprecated) so there isn't any built-in support.
I'm using Sequelize with Postgres and Angular.js in the front-end.
I'm setting up some routes to expect arrays in the response:
'getData': {
method: 'GET',
// isArray: true,
url: 'stuff/:id',
params: {id: '#id'}
}
However, when only one record is retrieved Sequelize seems to return an object directly
rather than an array with one object in it, which breaks the resource:
Error in resource configuration. Expected response to contain an array but got an object
Is there a way of setting up Sequelize to always return arrays even if there's only one record retrieved?
Or, a clean way of wrapping the data when it gets to ng-resource?
Thanks!
Angular should support object responses, but in any case:
Model.find() will return an object, Model.findAll() will return an array. You can just swap to using a findAll, if filtering on primary key it won't make much of a difference.
Model.find() also takes query parameters as it's second parameter so you should also be able to do Model.find({where: ..}, {plain: false}) but that hasn't been tested and isn't exactly public API.