John Davidson

php - BadMethodCallException: Project does not exist error

0 comments
Message:


I have two tables: projects and product


The problem is i cannot add new products from a project (one to many relationship)


I get the following error after creating a project with products: Method Illuminate\Database\Eloquent\Collection::project does not exist.


I need help solving this problem


Product.php


<?php
public function project()
{
return $this->hasOne(Project::class);
}
}


Project.php


<?php

public function products()
{
return $this->hasMany(Product::class, 'product_id');
}


Product migration file:


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{

if(!Schema::hasTable('product')){
Schema::create('product', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->text('description')->nullable();
$table->float('price')->nullable();

$table->foreignId('project_id')->nullable()->constrained('project')->onDelete('cascade');

$table->timestamps();
});
}
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('product');
}
};


ProjectController.php


 public function store(Request $request)
{
$project = new Project;

$project->name = $request->name;
$project->start_date = $request->start_date;
$project->due_date = $request->due_date;
$project->completed_date = $request->completed_date;
$project->actual_days = $request->actual_days;
$project->public_notes = $request->public_notes;
$project->private_notes = $request->private_notes;
$project->customer_id = $request->customer_id;
$project->project_category_id = $request->project_category_id;
$project->status = $request->status;
$project->user_id = $request->user_id;

// $project->products()->associate($request->products);

$products = Product::find($request->products);
// $products->project()->associate($project);

$products->project()->save($products);

//$project->products()->associate($project->id);

}


My Answer:
php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
protected $fillable = ['name', 'price'];

public function project()
{
return $this->belongsTo('App\Project');
}
}


In your `Product.php` model, make sure you have defined the `belongsTo` relationship correctly with the `Project` model.

If the issue persists, please provide more details or code snippets for further assistance.

Rate this post

3 of 5 based on 1075 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us