laravelguzzleomdbapi

Undefined index: Title laravel 6.0


am trying to save items of an array to db am getting the error above

Am fetching the array from the omdb api using the function index

 public function index()
    {
        $client = new Client();
        $uri = 'http://www.omdbapi.com/?s=water&apiKey=';
        $header = ['headers' => ['X-Auth-Token' => 'My-Token']];
        $res = $client->get($uri, $header);
        $data = json_decode($res->getBody()->getContents(), true);
  return $data;
    }

then am storing them using the function store

public function store(Request $request)
    {
        $movies = $this->index();
//        dd($this->index());

        collect($movies['Search']);
//        dd($movies);

             foreach($movies as $movie) {
//                dd($movie);
                Movie::create([
                    'title' => $movie['Title'],
                     'year' =>$movie['Year'],
                    'type' =>$movie['Type'],
                    'cover_photo' => $movie['Poster'],
                ]);

            }

    }
This is the output of dd($movie) 
array:10 [▼
  0 => array:5 [▼
    "Title" => "The Shape of Water"
    "Year" => "2017"
    "imdbID" => "tt5580390"
    "Type" => "movie"
    "Poster" => "https://m.media-amazon.com/images/M/MV5BNGNiNWQ5M2MtNGI0OC00MDA2LWI5NzEtMmZiYjVjMDEyOWYzXkEyXkFqcGdeQXVyMjM4NTM5NDY@._V1_SX300.jpg"
  ]
  1 => array:5 [▶]
  2 => array:5 [▶]

This is the output of dd($this->index());

array:3 [▼
  "Search" => array:10 [▼
    0 => array:5 [▶]
    1 => array:5 [▶]
    2 => array:5 [▶]
    3 => array:5 [▶]
    4 => array:5 [▶]
    5 => array:5 [▶]

Solution

  • Change this

    collect($movies['Search']);

    To

    $movies = collect($movies['Search']);