How do I get the following info with my json response:
current_page: 1,
from:1
I use pagination like this:
$rides = $user->rides()
->with('user', 'location', 'type')
->paginate(1);
It should be set by default. (https://laravel.com/docs/5.1/pagination)
(I am using vue.js)
Thankyou
Related
Using Nuxt3 and the Strapi v4 Plugin to create a blog.
Using the findOne function to retrieve ONE article.
However using the populate parameter to also retrieve relational parameters such as images:
findOne<Article>('articles', { populate: "images"}, id)
returns a list of ALL articles.
I want only my one article!
How do I get only the result for my given ID including the relations (images) when using the findOne function with the populate paramter?
Docs I consulted:
Strapi Docs on Parameters: https://docs.strapi.io/developer-docs/latest/developer-resources/database-apis-reference/rest/populating-fields.html#field-selection
Strapi Nuxt Docs: https://strapi.nuxtjs.org/usage
Your query syntax is wrong. findOne takes id as the second parameter and options as the third parameter as below:
Syntax:
findOne(uid: string, id: ID, parameters: Params) ⇒ Entry
Solution in Strapi:
const entry = await strapi.entityService.findOne('api::article.article', 1, {
fields: ['title', 'description'],
populate: { category: true },
});
Solution in Nuxt Strapi:
const entry = await findOne<Article>('articles', 1, {
fields: ['title', 'description'],
populate: { images: true },
});
Reference:
Entity Service Api
findOne - Nuxt Strapi
This problem looked so simple for me when I face with it yesterday! But when I didn't find similar question on google I realized it is not as simple as what I thought!!!So if there is any similar question that I didn't find since yesterday please let me know.
I'm trying to pass data from database using Laravel. I used UUID as primary key for Notifications table instead of auto-increment primary key (this is a default option for notifications table in Laravel!).
I can fetch and read all other columns as what they are but ID column which is UUID type comes as 0 OR 0 OR 5 or just any other single numbers however the real ID can be 1367dc99-ee67-4f0f-b0eb-c2215831d7db.
Frankly, I have no idea what is wrong either with the method I used in the Laravel or in Vue JS axios.
Is there any specific technique that I should use to read UUIDs from backend to frontend? Please help me with this.
I attached codes from Laravel and Vue JS Axios down below. If there is anything missing in my question please let me know.
Laravel Code
$notifications = Notifications::where('notifiable_id', auth()->user()->id)->orderBy('created_at', 'DESC')->get();
return response()->json(
[
"notifications" => $notifications
]
Vue JS Axios GET Method
data () {
return {
loading: false,
unreadNotifications: []
}
},
methods: {
async Notifications () {
this.loading = true
await axios.get('/user/notifications/unreads')
.then((response) => {
this.unreadNotifications = response.data
})
.finally (() => {
this.loading = false
})
}
}
the output is [ 0, 5 ]
If you want to display your id like this : 1367dc99-ee67-4f0f-b0eb-c2215831d7db, then modify your query by :
$notifications = DB::table('notifications')
->where('notifiable_id', auth()->user()->id)
->orderByDesc('created_at')
->get();
return response()->json([
"notifications" => $notifications
]);
i'm trying to send a patch request from my Vuetify data-table to Laravel & then to a mySQL DB.
Here's various code pieces from my controller.php, my api.php & the actual Vuetify file:
api.php:
Route::patch('machines/{id}', [
'as' => 'machines/{id}',
'uses' => 'MachineController#update'
]);
MachineController.php
$machines = Machine::find($request->id)->update();
the actual axios patch req. in the .vue file:
Object.assign(this.machines[this.editedIndex], this.editedItem);
axios.patch("machines/" + this.editedItem.id, {
editedItem: this.editedItem
})
In the Telescope payload section i'm getting the updated object, but i'm also getting a message:
"SQLSTATE[23000]:
Integrity constraint violation:
1048 Column cannot be null.
For all the columns.
I have also tried this syntax for a patch method:
if (this.editedIndex > -1) {
Object.assign(this.machines[this.editedIndex], this.editedItem);
axios
.patch("machines/" + this.editedItem.id)
.then(res => {
this.editedItem = Object.assign({}, this.editedItem);
})
.catch(err => {
console.log(err);
});
} else {
this.machines.push(this.editedItem);
}
this.close();
And i tried setting up the controller like this:
$machines = Machine::find($request->id);
$machines->machine_number = $request->input('machine_number');
$machines->machine_name = $request->input('machine_name');
$machines->machine_company = $request->input('machine_company');
$machines->machine_division = $request->input('machine_division');
$machines->machine_center = $request->input('machine_center');
$machines->machine_speed = $request->input('machine_speed');
$machines->save();
But I'm still getting the same error.
Can someone help me out, or at least point me in the right direction?
Thanks!
I have solved my issue: I was passing empty object with my axios.patch() request because i've set it up wrong. I've changed the object's structure to key:value pairs and voila, it worked!
I'll like to implemente the image upload system within my Laravel/VueJS project but I can't find a right way to do so. How can I set up my Controller function in order to handle this upload?
Edit:
This is my Editor configuration:
config: {
imageUploadParam: 'imageFile',
imageUploadURL: '/froala/upload/image',
imageUploadMethod: 'POST',
imageMaxSize: 5 * 1024 * 1024,
imageAllowedTypes: ['jpeg', 'jpg', 'png'],
}
And this is the function that handles the request:
public function uploadImage(Request $request)
{
$file = $request['imageFile'];
$name = $file->getClientOriginalName();
$name = strtolower(str_replace(' ', '', $name));
$path = $file->hashName();
$image = Image::make($file);
Storage::put("/threads/{$path}", (string) $image->encode());
$multimedia = Multimedia::create([
'name' => $name,
'path' => $path
]);
return ['link' => $multimedia->path];
}
I am using the Intervention Image library to handle the image upload.
Edit 2:
I'm getting an 419 error related with the csrf token. So, how can i pass it to the function? I know how to get it but using the imageUploadParams configuration of the editor is not working:
imageUploadParams: {
csrf: this.csrf
}
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
You need to pass the correct X-CSRF-TOKEN value to avoid the 419 error.
First check that you have the token defined the in the meta header with something like:
<meta name="csrf-token" content="{{ csrf_token() }}">
Early in your VueJS add:
var csrf_token = $('meta[name="csrf-token"]').attr('content');
Then add the following to your Froala config section:
config: {
requestHeaders: {
'X-CSRF-TOKEN': csrf_token
},
Media files should now pass through to your media upload function in Laravel.
From the documentation :
When an image is inserted into the WYSIWYG HTML editor, a HTTP request is automatically done to the server.
The specific URL that the request will be made to can be specified using the imageUploadURL config option.
Setup your routes.php file to properly direct the request to your controller of choice :
Route::post('/upload', 'FilesController#store');
Then, in your controller you can handle the image upload like you would normally. The important part is that you return the path to the file after you've saved it.
The returned JSON needs to look like: { "link": "path/to/image.jpg" }
Here is an example of what that could look like :
public function store(){
$filepath = request()->file('file')->store('images', 'public');
return ['link' => $filepath];
}
Of course, feel free to do any kind of validation or processing that you need.
instand of
imageUploadParams: {
csrf: this.csrf
}
use this
imageUploadParams: {
_token: this.csrf
}
Check this out From Documentation
I'm trying to integrate Twitter Typeahead into my Laravel (4.2.11) project (with Bootstrap 2.3.2).
I have results being returned as JSON (checked with Fiddler), but a single "undefined" is always displayed instead.
If I enter a search query that doesn't return any results, the "No Results" is displayed correctly.
//Simple query in Laravel
Route::get('/sidebar/clients/{q}', function($q)
{
$companies = DB::table('ViewCompanies')->select(array('CompanyID', 'FullCompanyName'))
->where('FullCompanyName', 'like', '%'. $q .'%')->get();
return Response::json(array('companies' => $companies));
});
//Javascript in page
var clients = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('FullCompayName'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
remote: {
url: '/sidebar/clients/%QUERY',
filter: function (parsedResponse) {
// parsedResponse is the array returned from your backend
console.log(parsedResponse);
return parsedResponse;
}
}
});
clients.initialize();
$('#clients .typeahead').typeahead({
hint: true,
highlight: true,
minLength: 3,
},
{
name: 'clients',
valueKey: 'CompanyID',
displayKey: 'FullCompanyName',
source: clients.ttAdapter(),
templates: {
empty: [
'<div class="tt-empty-message">',
'No Results',
'</div>'
],
header: '<h3 class="tt-tag-heading tt-tag-heading2">Matched Companies</h3>'
}
});
My console log using the above code:
what is the output of the parsedResponse you are logging? I think DB::table returns an object, not an array. Try to replace the response like this:
return Response::json(array('companies' => $companies->toArray()));
Then log the results and format them in the "filter" function in the Bloodhound object.
Hope it helps!
Thanks to Eduardo for giving me the idea of needing to parse my JSON into a JS array.
Doing a search revealed these two questions:
Twitter Typeahead.js Bloodhound remote returns undefined
Converting JSON Object into Javascript array
from which I was able to devise my one-line solution (full remove filter show):
filter: function (parsedResponse) {
console.log(parsedResponse);
var parsedResponse = $.map(parsedResponse, function(el) { return el; });
return parsedResponse;
}