feknaz feknaz - 6 months ago 37
PHP Question

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');

Answer

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();
}
Comments