I've got table Competitions and Competition_categories. Their relationship is
competitions.id = competition_categories.competition_id. I can create new competition with no problem but the Competition_categories is not saving any related records. My models:
Competition Model:
public function competition_category()
{
return $this->hasMany(CompetitionCategory::class, 'competition_id', 'id');
}
CompetitionCategory Model
public function competition()
{
return $this->belongsTo( Competition::class, 'competition_id' );
}
My Controller code - store method:
$request->validate([
'name' => 'required',
'frequency' => 'required|integer',
]);
$competition = Competition::create($request->all());
$competition_category = CompetitionCategory::create($request->all());
$competition_category->competition()->associate($competition);
$competition_category->save();
I've checked the documentation and other related questions but did not manage to get it working can you help me?
I'm expecting when I create new competitions new records to be saved in both tables. (New competitions are created successfully but no records in the category table. Also, one competition can have more than one category)
i can see a problem in your controller class, Laravel would advice not to create a class for pivot table, first you will need to update your question for better clarification, however here is a senerio and how to approach this.
Tables
Competition,
Categories,
Category_competition (pivot table)
reference for you
Competition Model:
public function category()
{
return $this->belongsToMany(Category::class, 'Category_competition','competition_id', 'category_id')->withPivot(['pivot attributes here']);
}
Category Model:
public function compitition()
{
return $this->belongsToMany(Compitition::class, 'Category_competition', 'category_id;'competition_id', 'id');
}
Then
$request->validate([
'name' => 'required',
'frequency' => 'required|integer',
]);
$competition = Competition::create($request->all());
$competition->category()->attach($category_attributes = []);
Related
maybe someone know how to insert pivot table in Laravel 8 automatically every i insert counselings table?
I have Model Counseling n to n Problem,
Input form
counselings table
problems table
Counselings Model
Problem Model
Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class', 'counselings')->findOrFail($request->id);
return response()->json($student);
}
public function store(Request $request)
{ dd($request->all());
$counseling = new Counseling();
$counseling->student_id = $request->student_id;
$counseling->user_id = Auth::user()->id;
$counseling->save();
if ($counseling->save()) {
$problem = new Problem();
$problem->id = $request->has('problem_id');
$problem->save();
}
}
You can insert into a pivot table in a few different ways. I would refer you to the documentation here.
Attaching
You may use the attach method to attach a role to a user by inserting
a record in the relationship's intermediate table:
Example:
$problem->counselings()->attach($counseling->id);
Sync
You may also use the sync method to construct many-to-many
associations. The sync method accepts an array of IDs to place on the
intermediate table. Any IDs that are not in the given array will be
removed from the intermediate table.
Example:
$problem->counselings()->sync($counselingsToSync);
Toggle
The many-to-many relationship also provides a toggle method which
"toggles" the attachment status of the given related model IDs. If the
given ID is currently attached, it will be detached. Likewise, if it
is currently detached, it will be attached:
Example:
$problem->counselings()->toggle($counselingsToToggle);
I would change your store() method to something like this :
public function store(Request $request)
{
$counseling = Counseling::create([
'student_id' => $request->student_id,
'user_id' => Auth::user()->id
]);
if($request->has('problem_id'){
$counseling->problems()->attach($request->problem_id);
//return something if problem id is in request
}
//return something if problem id is not there
}
I have 3 tables called games, products, game_product. And game_product is my pivot table
This is the structure.
id
game_id
product_id
1
1
1
1
1
2
30 Minutes ago I can attach the game_id and product_id correctly, then i changed nothing. And after I tried to create a new data, its give me this error message
Call to a member function games() on null
This is my model relationship
App\Models\Game.php :
public function products()
{
return $this->belongsToMany('App\Models\Product', 'game_product', 'product_id', 'game_id');
}
App\Models\Product.php :
public function games()
{
return $this->belongsToMany('App\Models\Game', 'game_product', 'game_id', 'product_id' );
And this is my create controller
public function productsNew(Request $request, $id)
{
$products = Product::find($id);
$new = Product::create([
'product_sku' => $request->product_sku,
'name' => $request->name,
'seller_price' => $request->seller_price,
'price' => $request->price,
'profit' => $request->price - $request->seller_price,
]);
$products->games()->attach($id);
$new->save();
notify("Product added successfully!", "", "success");
return redirect('admin/products/'.$id);
}
}
I try to post the id of game and product to pivot table game_id and product_id. What should I do to store the ID only without any other of value?
Just change the order of
$products->games()->attach($id);
$new->save();
to be
$new->save();
$products->games()->attach($id);
As a side note, you are creating a product. Just 1 product. So the variable name mustn't be pluralized as it is singular. $product
One final thing, if this function is just part of the CRUD, please follow the convention of naming functions to be: create/store/show/edit/update/destroy, makes your and everyone else's lives easier when asking questions.
Assuming there existed a One To Many relation where a User has Many Jobs, and the last record in the job table is the current job of the user. What is a better way of returning the users with their last jobs?
Here is what I have tried.
User Class
public function ejob(){
return $this->hasMany(Ejob::class);
}
Ejob Class
public function user(){
return $this->belongsTo(User::class);
}
API Controller Method
public function index()
{
return UserResource::collection((
User::with(
$this->particulars() // I want the last record from this line
)->orderBy('id', 'desc')->get() ));
}
Particulars Method
// I want the last record from this
private function particulars(){
return
[
'ejob.company:id,name',
'ejob.job:id,title',
'ejob.department:id,name',
'ejob.reporting:id,surname,first_name,other_name',
'ejob.employmentstatus:id,name',
'country:id,name',
'gender:id,name',
'state:id,name'
];
}
User Resource
public function toArray($request)
{
//return parent::toArray($request);
return [
'data' => [
'id' => $this->id,
'surname' => $this->surname,
'first_name' => $this->first_name,
'other_name' => $this->other_name,
'email' => $this->email,
'phone_number' => $this->phone_number,
'birthday' => $this->birthday->format('d-m-Y'),
'age'=> $this->birthday->age,
'ejob' => $this->whenLoaded('ejob'),
];
}
Currently, this returns a user with all related records from the ejobs table but I want just the last job.
You could define another relationship method for the same relationship but define it as a Has One instead of a Has Many:
public function currentJob()
{
return $this->hasOne(Ejob::class, ...)->latest();
// order by by how ever you need it ordered to get the latest
}
Then you could eager load that instead of the ejob relationship where needed.
You can use first() instead of get(). So it'll get a single model instance.
get() method give a collection and first() method give you a single model instance.
User::with(
$this->particulars()
)->orderBy('id', 'desc')->first()
Or you can use latest() to get the last inserted record.
User::with(
$this->particulars()
)->latest()->first()
->latest() fetches the most recent set of data from the Database. In short, it sorts the data fetched, using the created_at column to chronologically order the data.
Edit:-
As you wanted to get the last record of the relationship you can do as below.
User::with('ejob', function($query) {
return $query->latest()->first();
})->get();
// in your case
public function currentJob()
{
return $this->hasOne(Ejob::class, ...)->latestOfMany();
// order by by how ever you need it ordered to get the latest
}
// another example
public function latestPerformance()
{
return $this->hasOne(Performance::class)->latestOfMany();
}
You can group it by GROUP BY and then return all results.
There you will see job for each User
Create hasmany relatioship in vehicle model and insert data in vehicle and vehicle_staff table. data successfully insert in vehicle table but when store in vehicle_staff following error appear.
Error Comes:
Type error: Argument 1 passed to
Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an
instance of Illuminate\Database\Eloquent\Model, array given, called in
E:\xampp\htdocs\laravel-projects\collegeaccounting\app\Http\Controllers\Transport\VehicleController.php
on line 53
Vehicle Staff Table Schema:
Schema::create('vehicle_staffs', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->unsignedInteger('vehicles_id');
$table->unsignedInteger('staffs_id');
$table->boolean('status')->default(1);
});
Has Many Relationship on Vehicle Model:
class Vehicle extends BaseModel
{
protected $fillable = ['created_by', 'last_updated_by', 'number', 'type', 'model', 'description', 'status'];
public function staff(){
return $this->hasMany(Staff::class);
}
}
Store Function:
public function store(AddValidation $request)
{
$request->request->add(['created_by' => auth()->user()->id]);
$vehicle = Vehicle::create($request->all());
if ($request->has('staffs_id')) {
$staffs = [];
foreach ($request->get('staffs_id') as $staff) {
$staffs[$staff] = ([
'vehicles_id' => $vehicle->id,
'staffs_id' => $staff
]);
}
$vehicle->staff()->save($staffs);
}
$request->session()->flash($this->message_success, ' Created Successfully.');
return redirect()->route($this->base_route);
}
It seems you are creating many to many relationships, that is to say, a vehicle can belongs to many staffs, and a staff can have many vehicles. So, vehicle_staffs is a intermediate table (or pivot table) between vehicle model and staff model.
For Vehicle model, you should change the staff method to:
public function staff(){
return $this->belongsToMany(Staff::class, 'vehicle_staffs', 'vehicles_id', 'staffs_id');
}
To update many to many relationships, you can attach the staff ids to vehicle:
$vehicle->staff()->attach($staffIds);
and the code change of your store function:
if ($request->has('staffs_id')) {
$staffIds = $request->get('staffs_id');
$vehicle->staff()->attach($staffIds);
}
I don't know what version of Laravel you are using, so I assume you are on Laravel 5.x.
You should probably use saveMany() if you want to save more than one object. It takes a Collection or an array of Models as a parameter.
From the documentation:
If you need to save multiple related models, you may use the saveMany method:
$post = App\Post::find(1);
$post->comments()->saveMany([
new App\Comment(['message' => 'A new comment.']),
new App\Comment(['message' => 'Another comment.']),
]);
I have a relationship in my applications that is basically,
Many Organisations can have many Users, and many Users can have many Organisations.
So a many-to-many relationship, the organisation model relationship looks like this,
public function users() {
return $this->belongsToMany('User')
->where('admin', '>', 0)
->orWhere('basic', '>', 0)
->withPivot([
'start_date' => 'start_date as start_date',
'admin' => 'admin as admin',
'manager' => 'manager as manager',
'finance' => 'finance as finance',
'basic' => 'basic as basic',
'notifications' => 'notifications as notify'
])
->withTimestamps();
}
and my user model relationship to organisations looks like this,
public function organisations()
{
return $this->belongsToMany('Organisation');
}
I am having a huge problem with this relationship however, when I access this through project ( a project has one organisation, that has many users), I get a full list of users rather than just the users of the organisation for that project.
Why would this be? I think it is to do with my where clauses in the Users() function in my organisation model?
I don't see the reason you use all this code! I would say, Just make it simple:
Organisation class
public function users() {
return $this->belongsToMany('App\User');
}
User class
public function organisations() {
return $this->hasMany('App\Organisation');
}