Home > Software engineering >  cannot access specific JSON response in Laravel blade view
cannot access specific JSON response in Laravel blade view

Time:03-20

I have this JSON response that I get by using GuzzleHttp, this is my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class NewsController extends Controller
{
    public function index(){
        $api = "MY_API_KEY";
        $url = "https://newsapi.org/v2/top-headlines?country=id&apiKey=${api}";
        $news = [];
        $client = new \GuzzleHttp\Client();
        $res = $client->get($url);
        if($res->getStatusCode() == 200){
            $j = $res->getBody();
            $obj = json_decode($j, true);
            $news = $obj;
        }else{
            return "error";
        }
        return $news;
        return view('news', ["news", $news]);
    }
}

this is my web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\NewsController;


Route::get('/', [NewsController::class, 'index']);

this is the blade file where i want to display specific JSON properties from the response that i get

<x-app-layout>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>laravel news app</title>
</head>
<body>
    @foreach($news as $berita)
    <p>{{ $berita->articles->url }}</p>
    @endforeach
</body>
</html>
</x-app-layout>

Instead, it displays all the json response (all 38 results) and ignoring the foreach code above to get only the "articles url", and even if i leave my blade file empty with just the barebone html, it will still show all the json response.

  "status": "ok",
  "totalResults": 38,
  "articles": [
    {
      "source": {
        "id": null,
        "name": "Kompas.com"
      },
      "author": "Maya Citra Rosa",
      "title": "Viral Pernyataan Megawati Soal Minyak Goreng, Bisa Masak Direbus atau Kukus: Kok Njimet Gitu - Kompas.com - KOMPAS.com",
      "description": "Permasalahan minyak goreng di Indonesia saat ini juga menjadi sorotan Ketua Umum PDI Perjuangan (PDI-P) Megawati Soekarnoputri.",
      "url": "https://www.kompas.com/wiken/read/2022/03/19/065100381/viral-pernyataan-megawati-soal-minyak-goreng-bisa-masak-direbus-atau-kukus",
      "urlToImage": "https://asset.kompas.com/crops/ImX-yzl5mQ6OtLV0uBlrPfVDqOA=/296x148:891x545/780x390/data/photo/2021/09/24/614db35e81606.png",
      "publishedAt": "2022-03-18T23:51:00Z",
      "content": null
    },
    {
      "source": {
        "id": null,
        "name": "Detik.com"
      },
      "author": "Arief Ikhsanudin",
      "title": "Menakar Efek Kepindahan Sahrul Gunawan ke Golkar di Jawa Barat - detikNews",
      "description": "Sahrul Gunawan pindah dari Partai Nasdem ke Partai Golkar. Akan kah kepindahan Sahrul Gunawan ke Golkar bisa memberi efek pada raihan suara partai?",
      "url": "https://news.detik.com/berita/d-5990581/menakar-efek-kepindahan-sahrul-gunawan-ke-golkar-di-jawa-barat",
      "urlToImage": "https://awsimages.detik.net.id/api/wm/2022/03/09/menko-perekonomian-airlangga-hartarto-dan-wakil-bupati-bandung-sahrul-gunawan_169.jpeg?wid=54&w=650&v=1&t=jpeg",
      "publishedAt": "2022-03-18T23:17:01Z",
      "content": "Jakarta - Wakil Bupati Bandung Sahrul Gunawan pindah dari Partai Nasdem ke Partai Golkar. Akan kah kepindahan Sahrul Gunawan ke Golkar bisa memberi efek pada raihan suara partai?\r\nPendiri Lembaga Sur… [ 1678 chars]"
    },
      "source": {
        "id": null,
        "name": "Tribunnews.com"
      },
      "author": "rival al manaf",
      "title": "Prediksi Susunan Pemain Persebaya vs Persib Bandung, Pilihan Aji Santoso Tambal Absennya Marselino - Tribun Jateng",
      "description": "Aji Santoso dipastikan kehilangan bintang mudanya, Marselino jelang laga Persebaya vs Persib Bandung.",
      "url": "https://jateng.tribunnews.com/2022/03/19/prediksi-susunan-pemain-persebaya-vs-persib-bandung-pilihan-aji-santoso-tambal-absennya-marselino",
      "urlToImage": "https://cdn-2.tstatic.net/jateng/foto/bank/images/pemain-persebaya-bruno-moreira-saat-berhadapan-dengan-bek-persib-bandung.jpg",
      "publishedAt": "2022-03-18T22:34:25Z",
      "content": "TRIBUNJATENG.COM, BALI - Aji Santoso dipastikan kehilangan bintang mudanya, Marselino jelang laga Persebaya vs Persib Bandung.\r\nMarselino Ferdinan yang dipanggil mengikuti pemusatan latihan timnas In… [ 1597 chars]"
    },

CodePudding user response:

you have returned $news; before returning view.Also you are accessing object but returned array.Here is the complete code

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class NewsController extends Controller
{
    public function index(){
        $api = "Api Key";
    $url = "https://newsapi.org/v2/top-headlines?country=id&apiKey=${api}";
    $news = [];
    $client = new \GuzzleHttp\Client();
    $res = $client->get($url);
    if($res->getStatusCode() == 200){
        $news = json_decode($res->getBody());
    }else{
        return "error";
    }

    return view('news',compact('news'));
    }
}

and in view

@foreach($news->articles as $berita)
    <p>{{ $berita->url }}</p>
@endforeach
  • Related