Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
Laravel 7 One To Many Relations?

Below are all of the models, migrations and controller.

Donation Model

class Donation extends Model
{
    protected $guarded =[];

    public function users(){
        return $this->hasMany(User::class);
    }

    public function items(){
        return $this->belongsTo(DonationItems::class);
    }
}

Donation Items Model:

class DonationItems extends Model
{
    protected $guarded=[];

    public function donation(){
        return $this->hasMany(Donaition::class);
    }
}

Donation Items Migration:

public function up()
{
    Schema::create('donation_items', function (Blueprint $table) {
        $table->id();
        $table->string('category');
        $table->timestamps();
    });
}

Donation Migration:

public function up()
{
    Schema::create('donations', function (Blueprint $table) {
        $table->id();
        $table->string('item');
        $table->unsignedInteger('user_id');
        $table->unsignedInteger('donation_item_id');
        $table->timestamps();
    });
}

In my controller I want to access the items as follows:

$don = Donation::all();
$don->items;

But I'm unable to achieve this.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Its not working because laravel follows one rule for relationships:

Remember, Eloquent will automatically determine the proper foreign key column on the Comment model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Comment model is post_id.

So you can try by supplying local and foreign id

So it would look something like this

Donation Model class Donation extends Model { protected $guarded =[];

    public function users(){
        return $this->hasMany(User::class);
    }

    public function items(){
        return $this->belongsTo(DonationItems::class, 'donation_item_id', 'id');
    }
} 

Donation Items Model:

class DonationItems extends Model
{
    protected $guarded=[];

    public function donation(){
        return $this->hasMany(DonationItems::class, 'id', 'donation_item_id');
    }
}

I am writing from my head you might need to swap local and foreign ID's

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!