API Platform - Get collection where Author is User - api

I currently have an Offer entity which has an author property, like so :
#[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'offers')]
#[ORM\JoinColumn(nullable: false)]
private $author;
Currently, when I do a get request on /offers/, I get a collection of ALL the offers, which is normal.
I would want to only retrieve the offers where the author is the logged in user instead. (basically a findBy(['author'=>$this->getUser()]))
After searching on the internet I've been trying the following, which obviously is not working
#[ORM\Entity(repositoryClass: OfferRepository::class)]
#[ApiResource(
normalizationContext: [
'groups' => ['read'],
],
itemOperations: [
'get' => [
'security' => 'object.author == user',
]
],
collectionOperations: [
'get' => [
'security' => 'object.author == user',
]
]
)]
class Offer
{
...
This gives me the following error :
hydra:description: "Warning: Undefined property:
ApiPlatform\Core\Bridge\Doctrine\Orm\Paginator::$author"
Which tells me this is completely the wrong approach.
Kind of stuck here, any hint ?
Thank you.

Maybe a bit late but this is answered by implementing an "extension". That would allow the collection to be filtered to match only items with a specific condition (in your case, a User).
There's an old issue (here: https://github.com/api-platform/core/issues/1481).
And official documentation here: https://api-platform.com/docs/core/extensions/#example.

Related

Unexpected 404 Not Found Error in Laravel (5.8)

I have these lines in api.php
Route::apiResources([
'users' => 'Api\UserController',
'products' => 'Api\ProductController',
'categories' => 'Api\CategoryController',
]);
Route::get('/users/custom1', 'Api\UserController#custom1');
When I have them in this order and I call the route I get 404 Not Found.
But when I change the order, I get result:
Route::get('/users/custom1', 'Api\UserController#custom1');
Route::apiResources([
'users' => 'Api\UserController',
'products' => 'Api\ProductController',
'categories' => 'Api\CategoryController',
]);
This situation has frustrated me because I thought the error originated from the model and find method:
public function custom1()
{
$user2 = User::find(2);
return $user2;
}
Because I was checking the result in Postman and it shows the error like this when you ask for application/json as response:
{
"message": "No query results for model [App\\User] custom1",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
"file": "C:\\wamp64\\www\\laravel-api\\vendor\\laravel\\framework\\src\\Illuminate\\Foundation\\Exceptions\\Handler.php",
"line": 204,
"trace": [
{...
What is the reason of this change?
Because in both situations I can see the route in route:list.
Ok, I have realized the reason when I checked route:list with a clearer mind.
Laravel shows route:list in alphabetical order but actually the order we write in route file matters right?
So, it occured to me that if this line is coming first:
Laravel is trying to use custom1 as a route parameter.
So I must define this specific route before api resource routes:
Route::get('/users/custom1', 'Api\UserController#custom1');
Route::apiResources([
'users' => 'Api\UserController',
'products' => 'Api\ProductController',
'categories' => 'Api\CategoryController',
]);

How can I use another table for authentication in Laravel 7

Im very new with Laravel and had already seen many tutorials, so now I know little more. But I am struggling with a problem that I can't solve. I want to use another table(t_clients) that already exists in my DB instead of users table made by migration for authentication. I already read the documentation on website , so I changed in auth.php this:
'providers' => [
// 'users' => [
// 'driver' => 'eloquent',
// 'model' => App\User::class,
// ],
'users' => [
'driver' => 'database',
'table' => 't_clients',
],
],
Now when I try to login I get the next error : ErrorException Undefined index: id. So I tried the next one and this problem is temporary fixed, I changed the primary_key name in the table "t_clients" to "id" and login works. The original column name is "pk_client". But I want actually that the primary_key remains unchanged. I want actually that by authentication, Laravel search for "pk_client" and not "id". Does anyone know how I can fix this? I appreciate your help.
Spec project:
Laravel Framework 7.1.0
mysql Ver 8.0.18
This problem was fixed by making a Client EloquentModel and add de next lines:
protected $table = 't_clients';
protected $primaryKey = 'pk_client';
So the result should be:
class Client extends Authenticatable implements CanResetPassword
{
protected $table = 't_clients';
protected $primaryKey = 'pk_client';
use Notifiable;
}

How to pass parameters in https GET request for (Shopware) Rest API

As far as I understood, GET-Requests encode the parameters throught the url. I want to specify data that I get from the shopware REST-API (https://myshopurl/api/orders).
If I append ?limit=1, that works. But now I want to sort the results first.
The Shopware Rest API documentation says:
$params = [
'sort' => [
['property' => 'name']
]
];
$client->get('articles', $params);
or
$params = [
'sort' => [
['property' => 'orderTime'],
['property' => 'invoiceAmount', 'direction' => 'DESC']
]
];
$client->get('orders', $params);
but I am not sure how to build the URL from this information, because there are parameters within an array. Where do I have to write down the "sort" and do I have to use some brackets?
I hope somebody can help me :)
You simply need to put the filter in the url. Here is an example:
http://mydomain/api/orders?filter[0][property]=customer.email&filter[0][value]=my#domain.de
This is the exact example from here: https://developers.shopware.com/developers-guide/rest-api/#filter,-sort,-limit,-offset

Many-To-Many Association on Same Model using Waterline & Sails.js [duplicate]

I'm pretty new on Nodejs and sails.
I'm implementing a server which is similiar to Twitter. In user model, there should be 2 fields: follower and following, and the 2 fields are association of the model 'user' itself.
My question is when the model have only 1 association, either follower or following, it works.
However, when both follower and following included, there would be en error.
The code is something like this:
module.exports = {
attributes: {
alias: {
type:'string',
required: true,
primaryKey: true
},
pwd: {
type: 'string',
required: true
},
follower: {
collection: 'user',
via: 'alias'
},
following:{
collection: 'user',
via: 'alias'
}
}
The code will cause such error:
usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:115
throw new Error('Trying to associate a collection attribute to a model tha
^
Error: Trying to associate a collection attribute to a model that doesn't have a Foreign Key. user is trying to reference a foreign key in user
at References.findReference (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:115:11)
at References.addKeys (/usr/local/lib/node_modules/sails/node_modules/waterline/node_modules/waterline-schema/lib/waterline-schema/references.js:72:22)
For such usage your model definition is incorrect, namely the via keywords. As per the waterline associations docs the via keyword references the other side of the association. So, for a follower the other side is following and vice-versa. In other words:
follower: {
collection: 'user',
via: 'following'
},
following:{
collection: 'user',
via: 'follower'
}
You can check a full working example at: https://github.com/appscot/sails-orientdb/blob/master/test/integration-orientdb/tests/associations/manyToMany.selfReferencing.js

Filter products with API Magento in Ruby on Rails with Savon gem (SOAP)

I am using this code for my rails app with the API of Magento. Everything is fine except for one thing, i need filter the products by arguments of the Magento API but i don't know how :(
Obviously i have tested with more solutions (array, hash, etc), but
unsuccessful.
Pd: Sorry, my english is very limited
Links
Related case (fail): Adding a product using Savon to connect to Magento API
Example: http://www.polyvision.org/2011/10/02/using-magento-soap-api-with-ruby-and-savon.html
I know this is very late, but if anyone else is finding this thread, I've created a magento_api_wrapper gem that implements filters for the Magento SOAP API v2. You can find the code here: https://github.com/harrisjb/magento_api_wrapper
To summarize, if you want to use one of the Magento SOAP API simple filters, you can pass a hash with a key and value:
api = MagentoApiWrapper::Catalog.new(magento_url: "yourmagentostore.com/index.php", magento_username: "soap_api_username", magento_api_key: "userkey123")
api.product_list(simple_filters: [{key: "status", value: "processing"}, {key: created_at, value: "12/10/2013 12:00" }])
And to use a complex filter, pass a hash with key, operator, and value:
api.product_list(complex_filters: [{key: "status", operator: "eq", value: ["processing", "completed"]}, {key: created_at, operator: "from", value: "12/10/2013" }])
Spent ages getting this to work with Savon - there are no actual solutions on the web. Went and looked at the SOAP call and was missing :item
params = {:filter => {:item => {:key => "status", :value => "closed"}}}
result = client.call(:sales_order_list, message: { session_id: session_id, filters: params})
This will only return orders that are of status closed.
If you are looking to work with Magento and Rails, Gemgento might be what you need. It replaces Magento's front end with RoR.
http://www.gemgento.com
After you sync with Magento you can use the Gemgento::Product.filter method along with some scopes to easily search the EAV structure of Magento.
attribute = Gemgento::Attribute.find_by(code: 'color')
Gemgento::Product.filter({ attribute: attribute, value: 'red' })
The filter method can actually take all sorts of array/hash combos
filters = [
{ attribute: [attribute1, attribute2], value: %w[red yellow black] },
{ attribute: size_attribute, value: 'L' }
]
Gemgento::Product.filter(filters)