frenchbaguette
frenchbaguette

Reputation: 1339

Laravel. Update two tables at one POST method

I have this code right there, this code is working fine and data is successfully stored to table "reports". But I also want to update Users table and their field Credits also. How can I do this in this function ? I also have the relationship between these two tables "reports" and "users".

    public function giveCredits($id)
{
    $report = Report::where('id', $id)->first();
    $report->credits += Input::get('credits');
    $report->save();
    return redirect()->back();
}

Users Table

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name')->unique();
    $table->string('email')->unique();
    $table->string('password');
    $table->integer('credits');
    $table->enum('role', ['user', 'admin'])->default('user');
    $table->rememberToken();
    $table->timestamps();
});

Reports table

    Schema::create('reports', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->integer('credits');

Upvotes: 1

Views: 4907

Answers (1)

patricus
patricus

Reputation: 62368

You just need to add the logic to update the user (assuming you have a relationship method called user):

public function giveCredits($id)
{
    $report = Report::where('id', $id)->first();
    $report->credits += Input::get('credits');

    // if the report has a user, update it
    if ($report->user) {
        $report->user->credits += Input::get('credits');
        $report->user->save();
    }

    $report->save();
    return redirect()->back();
}

Upvotes: 1

Related Questions