在路由中使用模型时的HTTP ERROR 500

时间:2017-06-15 11:05:51

标签: php mysql laravel-5

在路线文件中使用模型后,我得到了HTTP ERROR 500。

这是路线文件代码:

use App\User;
use App\Address;


Route::get('/hesham', function () {
    return view('welcome');
});

Route::get('/insert', function(){
   $user = User::findOrFail(1); 
   $address = Address::create([
    'name'=>'1234 Housten av New York',
    'user_id' => $user->id
]) 
  $user->address()->save($address);
});

Home Route工作正常,但/ insert正在提供500 ERROR

以下是用户模型

user.php的

    <?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}


public function address(){

    return  $this->hasOne('App\Address');
}

这是地址模型 Address.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    //
}

public function user(){

    return  $this->belongsTo('App\User');
}

1 个答案:

答案 0 :(得分:0)

public function address(){

    return  $this->hasOne('App\Address');
}

反过来说:

public function user(){

    return  $this->belongsTo('App\User');
}

要将地址与用户关联,请执行以下操作:

Address::create([
    'name'=>'1234 Housten av New York',
    'user_id' => $user->id
])

修改

试试这个:

$address = new Address();
$address->user_id = $user_id;
$address->name = '1234 Housten av New York'
$address->save();