14
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Vinelab\Http\Client as HttpClient;
use App\Requests\SearchRequest;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class SearchResults extends Controller
{
    public function index()
    {
        return view('results.search-results');
    }

    public function store(Requests\SearchRequest $request)
    {

        $search_phrase = $request->input('search');

        $client = new HttpClient;

        $response = $client->get('https://www.reddit.com/search.json?q='. $search_phrase .'');

        $responseArray = $response->json();

        dd($responseArray);

        return view('results.search-results');

    }
}  

Using the above code, I make a call to the reddit API using this HTTP service

https://github.com/Vinelab/http/tree/master

The response that comes back gives me an Array of a lot of data, but I only want to get the title field from this and Parse it into a Laravel array that can be sent to a view where I will display the titles in a foreach loop.

I thought to maybe store the title of the results in the DB and then query the DB and send that through to the view. I am new to all of this so any assistance and theory will be appreciated.

Is there a way in Laravel 5.2 to convert the output of this JSON array to a usable array that can be compact and sent to the view?

1 Answer 1

60

You can do this, to convert json into Array format.

json_decode($response->content(), true);

and can access via this

$response[0]['title']

Sign up to request clarification or add additional context in comments.

8 Comments

I understand the logic here but I get this exception Call to undefined method Vinelab\Http\Response::first()
If I remove the first it throws Call to undefined method Vinelab\Http\Response::toArray(), this is directly from doing the HTTP call with the $client variable
I understand, you are using API, try this $response[0]['title']
Cannot use object of type Vinelab\Http\Response as array is the response, would this work on a JSON array? I have the array as JSON but now just want to convert it into a normal array that I can save in the DB with eloquent
try this, I am sure this will convert your JSON into normal array, json_decode($response->json(), true);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.