LoginSignup
3
1

More than 1 year has passed since last update.

【エラー備忘録】Laravelのログ出力時のエラー Object of class Laravel\Socialite\Two\User could not be converted to string 

Posted at

状況

Laravelで作ったアプリケーションに、OAithとLaravelのsocialiteを使ってGoogleアカウントでのログイン機能を実装していたときのこと。
Google認証後にコールバックを受け取るところで、画面にエラーが表示されました。

エラー内容

エラー文はこちら

ブラウザ
Object of class Laravel\Socialite\Two\User could not be converted to string 

「オブジェクト形式であるUserクラスを、文字列に変換できませんでした」という内容のようです。

原因の考察

エラーの原因となっているコードは、この部分でした。

LoginController
public function handleGoogleCallback()
    {
        // Google認証後の処理
        Log::debug('1');
        $googleUser = Socialite::driver('google')->stateless()->user();
        Log::debug($googleUser);    //この行がエラーの原因
        Log::debug('2');

handleGoogleCallbackメソッドが実行された際、Log::debug('1');はログ出力出来ていますが、$googleUserと'2'はログ出力できていませんでした。

Log::debugは文字列をログ出力するものですが、$googleUserの中身はオブジェクト形式。よって、先述の内容のエラーが出ていたようです。

解決法

ログ出力する際、print_r()を使って$googleUserを文字列に変換します。
※print_r()は、第二引数にtrueをとると、結果を文字列として関数の戻り値にすることができる。

LoginController
public function handleGoogleCallback()
    {
        // Google認証後の処理
        Log::debug('2');
        $googleUser = Socialite::driver('google')->stateless()->user();
        Log::debug(print_r($googleUser, true));   //書き換える
        Log::debug('3');

これでエラーはなくなり、また$googleUserの中身をログ出力することもできました。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1