Laravel Create Method Syntax Alternative - php

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.

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',
]);

Why store data with a relationship in Laravel?

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.

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.

Laravel-4 Validation

What is the best way to validate amount in laravel?
This is my code.
public static $rules = array(
'date' => 'required',
'payer' => 'required',
'category' => 'required',
'method' => 'required',
'creditAmount' => 'required|integer'
);
I don't want to limit the user. But amount could be like simple ditigs 33 or in the floating values like 33.45
May be you can can use as numeric:
public static $rules = array(
'creditAmount' =>'required|numeric'
));
I guess it works!
You probably want something like this:
public static $rules = array(
'date' => 'required',
'payer' => 'required',
'category' => 'required',
'method' => 'required',
'creditAmount' => array('required', 'regex:/^\d*(\.\d{2})?$/')
));
I'm no regex pro so you may need to tweak that part, but the point is you probably want to use the regex validator for something like this.

Categories