"Unable to generate an IRI for the item" with uuid - api

i change id generator to uuid generation like that :
`
#[ORM\Id]
#[ORM\GeneratedValue(strategy: 'CUSTOM')]
#[ORM\Column(type: 'uuid', unique: true)]
#[ORM\CustomIdGenerator(class: 'doctrine.uuid_generator')]
#[ApiProperty(identifier: true)]
private ?Uuid $id = null;`
`private Uuid $id;
public function getId(): Uuid
{
return $this->id;
}
`
but when i create/get or with other methods i get this error :
Unable to generate an IRI for the item of type \"App\\Entity\\MyEntity\"
My endpoints look like this :
#[GetCollection(
uriTemplate: '/bankroll',
normalizationContext: ['groups' => ['bankroll:list:view']],
provider: BankrollStateProvider::class
)]
#[Post(
uriTemplate: '/bankroll',
denormalizationContext: ['groups' => ['bankroll:add']],
processor: BankrollStateProcessor::class
)]
#[Get(
uriTemplate: '/bankroll/{id<\d+>}',
normalizationContext: ['groups' => ['bankroll:view']],
security: 'object.owner == user',
write: false,
)]
#[Put(
uriTemplate: '/bankroll/{id<\d+>}',
denormalizationContext: ['groups' => ['bankroll:edit']]
)]
#[Delete(
uriTemplate: '/bankroll/{id<\d+>}'
)]

Related

Swagger generate Post endpoint with notihing to write to user (front-end). i can find solution

Screen API platform POST end point
my question is about Api-platform, i create Categoriya entity and add denormalizationContext: and NormalizationContext: for create groups, and in final version the NormalizationContext is working but denormalizationContext is not working. in api platform shows POST endpoint but without example, in Categoriya-Write schema shows - entity's property is OnlyRead . i can not find my mistake in code.''
<?php
namespace App\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use App\Controller\ServisCreateAction;
use App\Repository\CategoriyaRepository;
use Doctrine\DBAL\Types\Types;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Serializer\Annotation\Groups;
#[ORM\Entity(repositoryClass: CategoriyaRepository::class)]
#[ApiResource(
collectionOperations: [
'get',
'CreateServis'=> [
'method' => 'post',
'path' => '/Categoriya',
'controller' => ServisCreateAction::class
]
],
itemOperations: [],
denormalizationContext:['groups'=>['user:Write']],
normalizationContext:['groups'=>['user:Read']]
)]
class Categoriya
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column()]
#[Groups(['user:Read'])]
private ?int $id = null;
#[ORM\Column(length: 255)]
#[Groups(['user:Write','user:Read'])]
private ?string $Xizmat_nomi = null;
#[ORM\Column(length: 255, nullable: true)]
#[Groups(['user:Write','user:Read'])]
private ?string $Xizmat_jinsi = null;
#[ORM\Column(length: 255, nullable: true)]
#[Groups(['user:Write','user:Read'])]
private ?string $Xizmat_turi = null;
#[ORM\Column]
#[Groups(['Read'])]
private ?int $Xizmat_narxi = null;
#[ORM\Column(type: Types::TEXT)]
#[Groups(['user:Write','user:Read'])]
private ?string $Xizmat_izohi = null;
#[ORM\Column]
#[Groups(['user:Write','user:Read'])]
private ?int $Xizmat_daqiqasi = null;
}

Laravel (API): I need to insert the post with Multiple Blog categories by using API Request (React)

I am trying to create a functionality for blog post which suppose to add by using front application which is built on react and my api which is built on Laravel (5.6),
I have tried couple of things, but unfortunately I am unable to figure out how can I attach multiple blog categories with single post
BlogPostAPIController.php
public function store(Request $request)
{
$BlogPosts = new BlogPosts;
$BlogPosts->tutor_id = $request->user()->tutor->id;
$BlogPosts->title = $request->title;
$BlogPosts->BlogCategories = $request->BlogCategories; /* Unknown column*/
$BlogPosts->slug = str_slug($request->title);
$BlogPosts->short_description = $request->short_description;
$BlogPosts->post_content = json_encode($request->post_content);
$BlogPosts->featured_image = $request->featured_image;
$BlogPosts->status = $request->status;
$BlogPosts->BlogCategories()->attach($request->blog_categories_id);
$BlogPosts->save();
return $BlogPosts::create($request->all());
}
BlogPostsModel.php
class BlogPosts extends Model{
public $table = 'blog_posts';
const CREATED_AT = 'created_at';
const UPDATED_AT = 'updated_at';
protected $dates = ['deleted_at'];
public $fillable = [
'tutor_id',
'title',
'slug',
'short_description',
'post_content',
'featured_image',
'status'
];
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'id' => 'integer',
'tutor_id' => 'integer',
'title' => 'string',
'slug' => 'string',
'short_description' => 'string',
'post_content' => 'string',
'featured_image' => 'string',
'status' => 'string'
];
/**
* Validation rules
*
* #var array
*/
public static $rules = [
];
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
**/
public function tutor()
{
return $this->belongsTo(\App\Models\Tutor::class);
}
public function BlogCategories(){
return $this->belongsToMany(BlogCategories::class);
}
// Category.php
public function BlogPosts(){
return $this->hasMany(BlogPosts::class);
}
}
BlogCategoryBlogPost.php
Schema::create('blog_categories_blog_posts', function(Blueprint $table) {
$table->integer('blog_categories_id')->unsigned();
$table->integer('blog_posts_id')->unsigned();
$table->foreign('blog_categories_id')->references('id')->on('blog_categories')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('blog_posts_id')->references('id')->on('blog_posts')->onUpdate('cascade')->onDelete('cascade');
});
API Response
Please find the screenshot for API response
You should save model before set relations, otherwise model doesn't have primary key (id) to set relations.
Better to use sync with belongsToMany relations (conveniently to update).
You should return saved model, now you create duplicate and return it.
Category belongsToMany Posts, and Post belongsToMany Categories.
Controller:
public function store(Request $request)
{
$BlogPosts = new BlogPosts;
$BlogPosts->tutor_id = $request->user()->tutor->id;
$BlogPosts->title = $request->title;
$BlogPosts->slug = str_slug($request->title);
$BlogPosts->short_description = $request->short_description;
$BlogPosts->post_content = json_encode($request->post_content);
$BlogPosts->featured_image = $request->featured_image;
$BlogPosts->status = $request->status;
$BlogPosts->save();
$BlogPosts->BlogCategories()->sync($request->blog_categories_id);
return $BlogPosts;
}
BlogPosts model:
public function BlogCategories(){
return $this->belongsToMany(BlogCategories::class, 'blog_categories_blog_posts');
}
BlogCategories model:
public function BlogPosts(){
return $this->belongsToMany(BlogPosts::class, 'blog_categories_blog_posts');
}

Symfony2 - using form validation in REST API project

In a Symfony REST API project and we are implementing a validation for the params passed to the end points.
I'm trying to using forms for this purpose but they don't seem to work as expected.
Given this end point as example:
GET /users/
which accepts a companyId as param
we want that this param is required and integer.
The controller
public function getUsersAction(Request $request)
{
$user = new User();
$form = $this->createForm(new UserType(), $user, array(
'method' => 'GET'
));
$form->handleRequest();
if ( ! $form->isValid()) {
// Send a 400
die('form is not valid');
} else {
die('form is valid');
}
}
The form type
class UserType extends FormType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->add('companyId', 'integer');
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
parent::configureOptions($resolver);
$resolver->setDefaults(array(
'data_class' => 'ApiBundle\Entity\User',
'csrf_protection' => false
));
}
/**
* #return string
*/
public function getName()
{
return ''; // if this is not empty, the form is not submitted at all
}
}
The validation.yml
ApiBundle\Entity\User:
properties:
companyId:
- Type:
type: integer
- NotBlank: ~
- NotNull: ~
The config.yml
framework:
validation: { enabled: true, enable_annotations: false }
The Problem
$form->isValid() in the controller is always true
Please replace with
$form->handleRequest();
to
$form->handleRequest($request);
I hope it will work.

How to use ElasticSearch MinHash plugin in NEST

I want to use MinHash elastic search plugin in NEST Elasticsearch.net.
How can I use minhash plugin in nest?
Create index with following mapping:
elasticClient.CreateIndex(descriptor => descriptor
.Index("my_index")
.Analysis(
analysis => analysis.Analyzers(bases => bases.Add("minhash_analyzer", new CustomAnalyzer
{
Tokenizer = "standard",
Filter = new[] {"minhash"}
})))
.AddMapping<IndexElement>(
mappingDescriptor =>
mappingDescriptor
.Properties(p => p
.String(s => s.Name(element => element.Message).CopyTo("minhashvalue"))
.Custom(new MiniHashMapping()))));
class MiniHashMapping : BinaryMapping
{
[JsonProperty("minhash_analyzer")]
public string Analyzer { get { return "minhash_analyzer"; } }
public MiniHashMapping()
{
Type = "minhash";
Name = "minhashvalue";
}
}
class IndexElement
{
public string Message { get; set; }
}
Index sample document:
elasticClient.Index(new IndexElement
{
Message = "Fess is Java based full text search server provided as OSS product."
}, descriptor => descriptor.Index("my_index"));
Tell elasticsearch to include fields in response:
var searchResponse = elasticClient.Search<IndexElement>(s => s.Query(q => q.MatchAll()).Fields("*"));
You can get hash value from searchResponse.Hits[..].Fields or searchResponse.FieldSelections.
Hope this helps.

Laravel 4.2 auth:attempt fails

I can't find this website and I can't figure out what is wrong with my code.
I am trying to get true for var_dump(Auth::attempt()), but it is always false.
This is my controllers method:
public function vartotojoPrisijungimoForma(){
$view = View::make('vartotojai.vartotojoPrisijungimoForma',
array('title'=>'Vartotojo Prisijungimas'));
var_dump(Auth::attempt(array('vardas'=>'aaaaa','pw'=>'aaaaa')));
return $view;
}
In my database the username is stored as vardas and password as pw
My auth.php file looks like this:
<?php
return array(
'driver' => 'eloquent',
'model' => 'Vartotojai',
'table' => 'vartotojai',
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
And the model file which is Vartotojai.php, looks like this:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Vartotojai extends ModeliuBaze implements UserInterface, RemindableInterface{
protected $table = 'vartotojai';
public $timestamps = false;
protected static $rules = array(
'vardas'=>'required|unique:vartotojai|min:4|regex:/[a-zA-Z]$/',
'pw'=>'required|alpha_num|between:4,8|confirmed',
'pw_confirmation'=>'required|alpha_num|between:4,8'
);
protected static $messages = array(
'required' => ':attribute laukelis tuscias!',
'min'=> ':attribute laukelyje galimas minimalus(:min) simboliu kiekis!',
'between' => ':attribute laukelis gali buti nuo :min - :max simboliu intervale!',
'vardas.regex'=> ':attribute turi atitikti siuos simbolius (a-zA-Z)',
'unique'=> 'Jau vartotojas su tokiu vardu uzregistruotas!',
'alpha_num'=>':attribute laukelyje galima rasyti tik skaicius ir raides!',
'confirmed'=>'Nesutampa slaptazodziai!'
);
protected $hidden = array('password');
public function getAuthIdentifier(){
return $this->getKey();
}
public function getAuthPassword(){
return $this->password;
}
public function getRememberToken(){
return $this->remember_token;
}
public function setRememberToken($value){
$this->remember_token = $value;
}
public function getRememberTokenName(){
return 'remember_token';
}
public function getReminderEmail(){
return $this->email;
}
}
I tried to check Hash:
public function vartotojoPrisijungimoForma(){
$view = View::make('vartotojai.vartotojoPrisijungimoForma',
array('title'=>'Vartotojo Prisijungimas'));
$pw = Vartotojai::find('5');
var_dump(Auth::attempt(array('vardas'=>'aaaaa','pw'=>'aaaaa')));
var_dump(Hash::check('aaaaa',$pw->pw));
return $view;
}
And hash check shows true.
You either need to change your password field from 'pw' to 'password' in your database. Laravel validates the credentials with 'password'.
OR
You could change this function to:
public function getAuthPassword(){
return $this->pw;
}
Then your attempt function should be:
var_dump(Auth::attempt(array('vardas'=>'aaaaa','password'=>'aaaaa')));