Jahid Mahmud Jahid Mahmud - 3 months ago 21
MySQL Question

Update Does not Work in laravel 5.1

Hello I am doing a project called Doctor management. I want to do update my doctor profile into two different table called doctor & User table. But I can't do it. Please Help me.
My Doctor Table

<?php

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

class CreateDoctorsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('doctors', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('division_id');
$table->integer('dcategory_id');
$table->integer('district_id');
$table->string('education');
$table->string('hospital');
$table->integer('fee');
$table->integer('phone');
$table->timestamps();
});

}

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


My User Table

<?php

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

class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}

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


My Controller is

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Auth;
class ProfileController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/

public function index()
{
$profile = Auth::user();
// if(!$profile) {
// return redirect()->route('logout')->with(['fail' => 'Profile Not Found']);
// }
return view('admin.article.index', compact('profile'));
}

/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/

public function getUpdate() {

$profile = Auth::user();

// $post = Post::find($post_id);
// if(!$post) {
// return redirect()->route('blog.index')->with(['fail' => 'Post Not Found']);
// }
return view('admin.article.edit',['post' => $post]);
}

public function postUpdate(Request $request ) {

$profile = Auth::user();


$this->validate($request, [
'name' => 'required|max:120',
'username' => 'required|max:80',
'email' => 'required',
'password' => 'required'
]);

// save users table
$profile = Auth::user();
// $user = new App\User;
$profile->name = $request->input('name');
$profile->email = $request->input('email');
$profile->username = $request->input('username');
$profile->password = $request->input('password');
$profile->update();

// save doctor table
DB::table('doctor')
->update(
'hospital' => $profile->input('hospital'),
'education' => $profile->input('education')
);


return redirect()->route('profile')->with(['success' => 'Profile Successfully Updated']);
}

// public function update(Request $request){
// $this->validate($request, [
// 'name' => 'required|max:120',
// 'username' => 'required|max:80',
// 'email' => 'required',
// 'password' => 'required'
// ]);

// // save users table
// $profile = Auth::user();
// // $user = new App\User;
// $profile->name = $request->input('name');
// $profile->email = $request->input('email');
// $profile->username = $request->input('username');
// $profile->password = $request->input('password');
// $profile->update();

// // save doctor table
// DB::table('doctor')
// ->update(
// 'id' => $profile->id,
// 'gender' => $profile->input('hospital'),
// 'age' => $profile->input('education')
// );

// // set a flush message and redirect()->back();
// return TRUE;

// return redirect()->route('profile')->with(['success' => 'Profile Successfully Updated']);
// }



public function create()
{
//
}

/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}

/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}

/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}

/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}


It did Not work Properly. Please help.Thanks in advance.

Answer

I think you have misspelled the table name.Its hould be doctors not doctor Update: added [] for array representaion

 DB::table('doctor')//change this to doctors
            ->update([
                'hospital'    =>  $profile->input('hospital'),
                'education'       =>  $profile->input('education')
            ]);  

But it should have an error stating that doctor table is not found.

Update: As @KmasterYC pointed out, you are also missing the id to select the row to be updated. Here is the updated code:

DB::table('doctors')
                ->where('id',$profile->id)
                ->update([
                    'hospital'    =>  $profile->input('hospital'),
                    'education'       =>  $profile->input('education')
                ]);

Update: Using Models in Laravel

Adding Foreign key: Reference : Laravel Migration To add foreign key in your migration replace your up() method in Doctor table's miration with following. Explaination inline.

public function up()
{
    Schema::create('doctors', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id');// column to refer to user table's id
        $table->string('name');
        $table->integer('division_id');
        $table->integer('dcategory_id');
        $table->integer('district_id');
        $table->string('education');
        $table->string('hospital');
        $table->integer('fee');
        $table->integer('phone');
        $table->timestamps();
        //following line will add the the foreign key
        $table->foreign('user_id')->references('id')->on('users');
    });

}

Creating Models: Reference : Laravel Eloquent Assuming you are storing your models in app directory.

Doctor Model:(Doctor.php)

namespace App;

use Illuminate\Database\Eloquent\Model;

class Doctor extends Model{
     protected $fillable = array('name','hospital','education','fee','phone');
     //method to define Doctor-User relationship
     public function User(){
        return $this->belongsTo('App\Models\User');
     }
}

User Model; (User.php)
(Since you already have this model, you don't need to create it)

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model{
     protected $fillable = array('name','username','email','password');
     //method to define User-Doctor relationship
     public function Doctor(){
        return $this->hasOne('App\Models\Doctor');
     }
}

Controller:
Replace your postUpdate() method with following to use Models. Explaination inline.

public function postUpdate(Request $request ) {

        $profile = Auth::user();

        $this->validate($request, [
            'name' => 'required|max:120',
            'username' => 'required|max:80',
            'email' => 'required',
            'password' => 'required'
            ]);

         // save users table
        $profile = Auth::user();
        // $user = new App\User;
        $profile->name = $request->input('name');
        $profile->email = $request->input('email');
        $profile->username = $request->input('username');
        $profile->password = $request->input('password');
        $profile->update();

        // replace the following part
        /*
        DB::table('doctor')
        ->update(
            'hospital'    =>  $profile->input('hospital'),
            'education'       =>  $profile->input('education')
        );  */

        $profile->Doctor()->update($request->only(['hospital','education'])); //This will update your Doctor model related to loged in user

        return redirect()->route('profile')->with(['success' => 'Profile Successfully Updated']);
    }