Why store data with a relationship in Laravel? - php

I have a BlogImage model and a Blog model. Now I want to know if it's correct to use the create method with the relation and why it is used this way like below:
$blogImage = new BlogImage();
$blogImage->blog()->create([
//this is making the blog for me
'title' => $request->title,
'content' => $detail,
'category_id' => $request->category_id,
'author' => Auth::user()->id,
'meta_description' => $request->title,
'meta_image' => $meta_image,
]);
Also, I want to know what is the difference between this method and the normal form, which is:
Blog::create([
'title' => $request->title,
'content' => $detail,
'category_id' => $request->category_id,
'author' => Auth::user()->id,
'meta_description' => $request->title,
'meta_image' => $meta_image,
]);

In short: in the first example you're creating the Blog instance and linking it to blogImage, but in the second example you're only creating an instance of the Blog model.
In the second example you would have to attach the new Blog instance to blogImage after creating it with $blogImage->blog()->attach($blog->id).
The first example's create method is described here and the second example's is described here in Laravel's documentation.
Either method is correct. It's just shorter to use the first example.

Related

How to create mongodb collection on runtime while executing Yii2 code?

I need to create mongodb collection while executing code, by checking whether the collection is exists or not.
I tried below things
Yii::$app->db->createCommand()-> createCollection("collection_name");
but collection not created.
Please help.
Issue resolved..
Yii::$app->db->createCommand()->createCollection("collection_name")->execute();
and index will added for collection as,
$collectionName = Yii::$app->db->getCollection("collection_name");
$collectionName->createIndexes([
'key' => ['id' => 'int'],
'name' => 'id_index'
],
[
'key' => ['id' => 'int', 'category' => 'text'],
'name' => 'id_category_index',
]);

Laravel Create Method Syntax Alternative

I'm building relationships between the users and posts tables. I'm wondering if there is a way to write this differently than this syntax?
$request->user()->posts()->create([
'body' => $request->body
]);
Using syntax like this below how can achieve the same result as above?
Post::create([
'body' => $request->body,
]);
I'm curious because I like to keep the same patterns.
You could do
Post::create([
'user_id' => Auth::user()->id,
'body' => $request->body,
]);
But for relations it's best to do your first solution.

Laravel, blank record using create method

I have a problem with create() method in Laravel.
Every time when I try to create new record in database using this code:
$website = Website::create([
'user_id' => auth()->user()->id,
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
'user_id' => $request->subcategory_extra_id,
]);
the column user_id (in database) equals to 0 whereas my id is 1. Of course I have fillable variable in my model:
protected $fillable = [
'user_id',
'name',
'url',
'description',
'subcategory_id',
];
I tried to use constant value instead of auth()->user()->id but I still have 0 as user_id in database. Using save() method solves this problem but I prefer to use create().
You have listed user_id twice in your keys. The 2nd time, the integer is empty.
'user_id' => $request->subcategory_extra_id,
//observe
Why you used 'user_id two times in your code?
one is
'user_id' => auth()->user()->id,
and another one is
'user_id' => $request->subcategory_extra_id,
Just use one instead of two. And try to use the follwing way:
'user_id' => Auth::user()->id;
Remember: in this case you have to use the namespace of Auth class.
Hope it will work
try to use this
use Auth namespace
and then
$website = Website::create([
'user_id' => Auth::user()->id,
'name' => $request->name,
'url' => $request->url,
'description' => $request->description,
'subcategory_id' => $request->subcategory_id,
]);

CakePHP 3.x - Link and save associations with 3 models through one model

I am using CakePHP version 3.x.
I need to link three models (Trackers, Articles, Mentions) through one Model (TrackersArticlesMentions).
Here my relations definition:
TrackersTable.php
$this->belongsToMany('Mentions', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
$this->belongsToMany('Articles', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
ArticlesTable.php
$this->belongsToMany('Mentions', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
$this->belongsToMany('Trackers', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
MentionsTable.php
$this->belongsToMany('Articles', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
$this->belongsToMany('Trackers', [
'through' => 'TrackersArticlesMentions',
'saveStrategy' => 'append',
]);
TrackersArticlesMentionsTable.php
$this->belongsTo('Trackers', [
'foreignKey' => 'tracker_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Articles', [
'foreignKey' => 'article_id',
'joinType' => 'INNER'
]);
$this->belongsTo('Mentions', [
'foreignKey' => 'mention_id',
'joinType' => 'INNER'
]);
So far everything is working perfectly when I want to find my data and include (aka contain) them.
Unfortunately, when I want to link them, I should be able to use the function link and do something like this:
$this->Trackers->link($trackerEntity, [$articleEntity, $mentionEntity]);
But it doesn't work, the function link expects as a second parameter:
list of entities belonging to the target side of this association
I may be wrong, but the function seems to be made to link only two entities, the second parameter is only of an array of the same entity...
I found a solution by creating a function in the TrackersArticlesMentionsTable like this:
public function createLink(\App\Model\Entity\Tracker $trackerEntity, \App\Model\Entity\Article $articleEntity, \App\Model\Entity\Mention $mentionEntity)
{
return $this->findOrCreate([
'tracker_id' => $trackerEntity->get('id'),
'article_id' => $articleEntity->get('id'),
'mention_id' => $mentionEntity->get('id'),
]);
}
But I would like to do it "properly".
Does someone have any suggestion?
Thank you!
The link() method is ment to link a single association source side entity, to multiple (usually distinct) association target side entities, for example, link a single Post to multiple Tags, which would be done via the Tags association.
So that means that via $this->Trackers->link() (I assume that $this is a table object, and therefore $this->Trackers is an association object), you could link a single Mention or Article to multiple (distinct) Trackers.
The usage of link() that you have in mind is not supported, so you have to go with something like the solution that you came up with, eg create and save a TrackersArticlesMention entity on your own - it's perfectly fine to do that.

How to organize parsing and validation of REST API parameters?

I have a rest api that has many parameters via the query string. I am wondering if someone knows of a design pattern or has a nice way of organizing all the parameters (Objects, functions, array, json). Right now I am parsing and validating all my parameters in the same function, very ugly code.
Ideally I would like some way to handle the parameters similar to a database ORM or even a config file/array/json. However, I have tried to come up with a solution to this without any luck.
Any insight would be appreciated!
Example of my thoughts:
<?php
...
$parameters = [
// ?fields=id,name
'fields' => [
'default' => ['id', 'name'],
'valid' => ['id', 'name', 'date],
'type' => 'csv', // list of values (id & name)
'required' => ['id'],
'replace' => ['title' => 'name'], // if the database & api names don't match
'relation' => null, // related database table
],
// ?list=true
'list' => [
'default' => ['false'],
'valid' => ['true', 'false'],
'type' => 'boolean' // single value (true or false)
'required' => [],
'replace' => [], // if the database & api names don't match
'relation' => 'category', // related database table
],
....
];
Seems to me like you are looking for a validation library. My favorite is Symfony's: https://github.com/symfony/validator. I know Zend Framework 2 also has a validation component. I haven't used it personally, but I expect that to be very good too.
Example from the symfony/validator readme:
<?php
use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert;
$validator = Validation::createValidator();
$constraint = new Assert\Collection(array(
'name' => new Assert\Collection(array(
'first_name' => new Assert\Length(array('min' => 101)),
'last_name' => new Assert\Length(array('min' => 1)),
)),
'email' => new Assert\Email(),
'simple' => new Assert\Length(array('min' => 102)),
'gender' => new Assert\Choice(array(3, 4)),
'file' => new Assert\File(),
'password' => new Assert\Length(array('min' => 60)),
));
$input would be $_GET or something obtained with parse_str etc. It is also possible to define the validation rules in some other format, such as YAML.

Categories