如何在Laravel

时间:2017-03-30 18:30:46

标签: php laravel

在将值保存到数据库时如何捕获值时感到很困惑。这是laravel 5.4

在app \ Http \ Controllers \ Auth中,我想捕获保存到数据库的输入值。

protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged. 

    return User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

     $name = $data['name'];

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged. 
}

我想要捕获的原因是因为我想在创建用户后立即将捕获的输入数据的curl请求发送到第三方应用程序。

谢谢。

2 个答案:

答案 0 :(得分:1)

不是返回创建的User实例,而是执行此操作:

$user = User::create([
    'name' => $data['name'],
    'username' => $data['username'],
    'email' => $data['email'],
    'password' => bcrypt($data['password']),
]);

// Do stuff here
$name = $user->name;

return $user;

答案 1 :(得分:1)

returning声明

之后,您无法执行任何操作
  

如果在函数内调用,则立即返回语句   结束当前函数的执行,

相反,您需要将其存储在变量中,然后在执行日志记录后将其返回,如下所示:

protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged. 

    $createdUser = User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);

     $name = $createdUser->name;

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged.

     return $createdUser;
}

更新

只要您不需要从数据库返回的数据,您可以简单地移动这两行:

$name = $data['name'];

Log::info('Showing user profile for user: '.$name);

返回创建对象之前:

protected function create(array $data)
{

    Log::info('Adding the User ');  //  This is getting logged. 

    $name = $data['name'];

     Log::info('Showing user profile for user: '.$name);  //  This is not getting logged. 

    return User::create([
        'name' => $data['name'],
        'username' => $data['username'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
    ]);
}