LoginSignup
0
0

More than 1 year has passed since last update.

【エラー解決】Trying to access array offset on value of type null

Posted at

はじめに

 Laravelでちょっとハマったので一応備忘録として。

Trying to access array offset on value of type null

Laravelでview composerに値を渡そうとしたときにぶつかりました。

AppServiceProvider.php
view()->composer('*', function($view){
     $user = \Auth::user();
     $post_model = new Post();
     $post = $post_model->get_post($user['id']);
     $view->with('user',$user)->with('post',$post);
});

我らがGoogle先生によると、
「null型の値で配列オフセットにアクセスしようとしています」
だそうです。
どうやらまだユーザー情報がない状態でget_postメソッドの引数に\$user['id']を渡しているのが原因のようです。
それでは、あらかじめ配列を定義してあげましょう。

AppServiceProvider.php
view()->composer('*', function($view){
     $user = \Auth::user();
     if(empty($user)){
         $user = ['id' => 0]
     }
     $post_model = new Post();
     $post = $post_model->get_post($user['id']);
     $view->with('user',$user)->with('post',$post);
});

\$userがない場合に\$user['id']を定義してやればエラーはなくなるはずです。

終わりに

 無事に解決できました!

0
0
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
0
0