Creating a item with multiple relations in 1 call - laravel

So I have a project table:
Schema::create('projects', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->string('name');
$table->string('reference')->nullable();
$table->date('started')->nullable();
$table->date('ended')->nullable();
$table->string('industry')->nullable();
$table->string('operatives')->nullable();
$table->timestamps();
$table->softDeletes();
});
And I have an hours table:
Schema::create('hours', function (Blueprint $table) {
$table->increments('id');
$table->string('hours');
$table->date('date')->nullable();
$table->text('notes')->nullable();
$table->integer('project_id');
$table->integer('user_id');
$table->softDeletes();
$table->timestamps();
});
Now, is there anyway to create an association with both the project_id and user_id in one call?
I know I can do the following (adding the user_id to the hours):
$hours = [
'hours' => $request->hours,
'date' => $request->date,
'operatives' => $request->operatives,
'notes' => $request->notes,
'user_id' => auth()->user()->id,
];
$create = $project->hours()->save(new $this->hour($hours));
But I am trying to do something like so:
$hours = [
'hours' => $request->hours,
'date' => $request->date,
'operatives' => $request->operatives,
'notes' => $request->notes,
];
$create = $project->hours()->save(auth()->user()->save($hours));
Both user and project have the same hours relation in their classes:
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function hours(): HasMany
{
return $this->hasMany(Hour::class);
}
Is this possible, if so, how would I go about doing it?

I think the best way to handle this would be to separate the saving of Hours as an independent instance of the model and then sync it with both like so:
$hour = Hour::create($hours);
$project->hours()->syncWithoutDetaching([$hour->id]);
$user->hours()->syncWithoutDetaching([$hour->id]);

Related

How to call id from table in another table in laravel-8

Here I have three tables named user, product, project
In the project table, I have two foreignId named user_id and product_id
I want to show project table data using the index method in ProjectController.php
Here I can call user_id in the index method but I cant call product_id. Thanks for help
This is my index method in ProjectController.php
How to write where for product_id? I can`t get product_id value
public function index()
{
$projects = Project::where('user_id',auth()->user()->id)->where('product_id')->latest() ->paginate(20);
return view('projects.index', compact('projects'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
This is products table products.php
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->text('detail');
$table->string('color');
$table->string('image');
$table->string('logo');
$table->unsignedBigInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
This is projects table projects.php
Schema::create('projects', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('chapter_name', 255)->nullable();
$table->string('sub_section_name', 500)->nullable();
$table->string('title_1', 255)->nullable();
$table->string('description_1', 5000)->nullable();
$table->string('image_1', 255)->nullable();
$table->string('image_2', 255)->nullable();
$table->string('image_3', 255)->nullable();
$table->string('title_2', 255)->nullable();
$table->string('description_2', 5000)->nullable();
$table->string('title_3', 255)->nullable();
$table->string('description_3', 255)->nullable();
$table->string('video_1', 255)->nullable();
$table->string('video_2', 255)->nullable();
$table->string('video_3', 255)->nullable();
$table->unsignedBigInteger ('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
// $table->foreignId('product_id')->nullable();
$table->unsignedBigInteger('product_id')->references('id')->on('products')->onDelete('cascade');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('updated_at')->nullable();
});
This is ProjetcImport.php
return new Project([
'chapter_name' => $row['chapter_name'],
'sub_section_name' => $row['sub_section_name'],
'title_1' => $row['title_1'],
'description_1' => $row['description_1'],
'image_1' => $row['image_1'],
'image_2' => $row['image_2'],
'image_3' => $row['image_3'],
'title_2' => $row['title_2'],
'description_2' => $row['description_2'],
'title_3' => $row['title_3'],
'description_3' => $row['description_3'],
'video_1' => $row['video_1'],
'video_2' => $row['video_2'],
'video_3' => $row['video_3'],
'user_id' => auth()->user()->id,
'product_id' => Product::where('user_id',Auth::id())->pluck('id'))
// 'product_id' => id()->id
]);
Project::whereIn('product_id',Products::where('user_id',Auth::id())->pluck('id')->toArray())->latest()->paginate(20);
I hope it would work for you.

Laravel Many to Many attach?

I'm trying to create or attach data to table called "user_votes", but I dunno why the connections between "Vote" and "User" doesn't work.
user_votes table
Schema::create('user_votes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->bigInteger('vote_id')->unsigned();
$table->string('name');
$table->string('page', 100)->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('vote_id')->references('id')->on('votes');
});
Vote model:
public function user_votes()
{
return $this->belongsToMany(User::class, 'user_votes');
}
User model:
public function user_votes()
{
return $this->belongsToMany(Vote::class, 'user_votes');
}
store controller:
auth()->user()->user_votes()->attach([
'name' => $option->name,
'page' => $option->page
]);
Thanks for any ideas.
Please try the below code hope it will help you.
$voteId = 1;
auth()->user()->user_votes()->attach($voteId => [
'name' => $option->name,
'page' => $option->page
]);

Does not change default value in mysql (laravel 5,5)

this is my code in users tabel (migrations)
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('level')->default('user');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
when I want to change level manually like below code
return User::create([
'level' => 'admin',
'name' => 'emad',
'email' => 'emad#gmail.com',
'password' => bcrypt('123456')
]);
In the level field, the same user value is saved and admin dosent save.
I do not know why?
Judging from the little code here, i would say you haven't added the level column to the fillable model variable.Like so:
protected $fillable = ['level','any_other_field_you_want_to_assign'];
Add this line of code to the top of your User model class
Check the documentation here

Storing foreign key value in database (laravel)

I am new to laravel. i am having difficulties to store foreign key value in database. I have read the documentation, searched on stackoverflow. But its confusing me more.
I have a User table and an idea table. User can create many idea. Let me show the code:
Controller function:
public function storePost(IdeaRequest $request) {
Idea::create([
'title' => $request->input('idea_title'),
'user_id' => $request->hasMany('user_id'),
'image' => $request->file('idea_image')->move('images'),
'info' => $request->input('idea_info'),
'communitySelection' => $request->input('selection'),
'location' => $request->input('idea_location'),
'goal' => $request->input('idea_goal'),
'description' => $request->input('idea_description')
]);
}
Idea Model:
class Idea extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'idea_title', 'idea_info','user_id', 'idea_image', 'idea_description', 'duration', 'idea_goal', 'pledge_amount', 'set_equity',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token',
];
public function Post() {
return $this->hasMany('User');
}
}
Idea Migration:
public function up()
{
//
Schema::create('ideas', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('idea_title');
$table->string('idea_info', 150);
$table->string('idea_image');
$table->string('selection');
$table->longText('idea_description');
$table->string('idea_location');
$table->integer('idea_goal')->unsigned();
$table->integer('pledge_amount')->unsigned();
$table->string('set_equity')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
User Migration:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name',50);
$table->string('email')->unique();
$table->string('password',32);
$table->string('profile_picture')->nullable();
$table->string('address');
$table->string('phone_number',15);
$table->boolean('status')->nullable();
$table->string('user_type',15);
$table->string('credit_card',16)->unique();
$table->rememberToken();
$table->timestamps();
});
}
It can be seen that foreign key is being set. I am unable to store the value of foreign key on a user table. Any help would be appreciated.
In the Idea Migration, you can declare the foreign key like this
public function up()
{
//
Schema::create('ideas', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('idea_title');
$table->string('idea_info', 150);
$table->string('idea_image');
$table->string('selection');
$table->longText('idea_description');
$table->string('idea_location');
$table->integer('idea_goal')->unsigned();
$table->integer('pledge_amount')->unsigned();
$table->string('set_equity')->nullable();
$table->rememberToken();
$table->timestamps();
});
//Declare foreign key
Schema::table('ideas', function(Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')
->onDelete('restrict')
->onUpdate('restrict');
});
}
I do not agree with the relation you added in the Idea Model. You should use belongsTo instead of hasMany. And according to the comments, change Post() to User() .
public function User() {
return $this->belongsTo('User');
}
If so, you need also change 'user_id' => $request->hasMany('user_id') in the Controller function.

Laravel 5 How to add multiple foreign key constraints to a User on creation?

I now know that I can create a User using the haveMany relationship between a Region and User by doing this:
$region = Region::find($data['region_id']);
$region->users()->create([
'username' => $data['username'],
'email' => $data['email'],
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'password' => bcrypt($data['password']),
]);
But what if there are multiple foreign keys, how do you create a user without making them fillable for more than 1 foreign key constraint? What if there were 3 or 4?
Example of the relationships setup in the different models:
Region hasMany Users, or
User belongsTo a Region
Location hasMany Users, or
User belongsTo a Location
A stripped down version of my migration looks like this if it helps to understand the relationships better:
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->integer('region_id')->unsigned();
$table->integer('location_id')->unsigned();
$table->timestamps();
$table->foreign('region_id')
->references('id')
->on('regions');
$table->foreign('location_id')
->references('id')
->on('locations');
});
Schema::create('regions', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 100);
$table->timestamps();
});
Schema::create('locations', function (Blueprint $table) {
$table->increments('id');
$table->string('street_address', 100);
$table->string('city', 50);
$table->string('province', 50);
$table->string('country', 50);
$table->string('postal_code', 10);
$table->timestamps();
});
Example of Region and Location Models:
/**
* Region may have many users.
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function users()
{
return $this->hasMany('App\User');
}
/**
* Location may have many users.
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function users()
{
return $this->hasMany('App\Location');
}
I assume you have a model for Region and Location. Each of your region has an id and location has an id, then just add
$this->hasMany('where your Region model is', 'region_id', 'id');
$this->hasMany('where your Location model is', 'location_id', 'id');
to your User model
Reference: http://laravel.com/docs/5.0/eloquent#one-to-many
Edit: You can also do in any of your model
if ($this->create()) {
return (new Model())->create(the params you need in another model);
}

Resources