Reputation: 2238
I am currently developing an api for my site to work with google maps. I have successfully developed an api with help from the community. But it only outputs a single page. I need it to be dynamic, because results will be based off of input from the user. As it stands my controller looks like this
<?php
namespace App\Http\Controllers;
use App\Post;
use App\Http\Requests;
class ApiController extends Controller
{
public function index() {
$results = [];
foreach (Post::all() as $post)
{
$results[] = [
'id' => $post->id,
'marketname' => $post->subtitle,
];
}
return ['results' => $results];
}
}
but this isn't dynamic.
I was thinking of copying my search and modifying it. it looks like this
<?php
namespace App\Http\Controllers;
use App\Jobs\TagIndexData;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Post;
use App\Video;
use App\Tag;
use App\Http\Controllers\Controller;
class TagController extends Controller
{
public function index(Request $request)
{
$query = $request->get('q');
$posts = Post::where('title', 'LIKE', "%{$query}%")
->orwhere('subtitle', 'LIKE', "%{$query}%")->get();
$videos = Video::where('title', 'LIKE', "%{$query}%")
->orwhere('subtitle', 'LIKE', "%{$query}%")->get();
$tag = $request->get('tag');
$data = $this->dispatch(new TagIndexData($tag));
$layout = $tag ? Tag::layout($tag) : 'tags.layouts.index';
return view($layout, $data)->withPosts($posts)->withVideos($videos);
}
}
But I don't understand how to store json in mysql nor how to query it and output it Any help would be greatly appreciated.
To be clear on what I want. I want a person to enter their zipcode or address and then return a google map populated with markers indicating nearby events.
I am trying to modify a tutorial I did using a farmers market api mashed up with googles. Part of the javascript looks like this
accessURL="http://search.ams.usda.gov/farmersmarkets/v1/data.svc/zipSearch?zip=" + userZip/address;
where userZip/address is input that I want to use to populate the google map
any advice on how I should structure this is welcomed
Upvotes: 1
Views: 474
Reputation: 10618
Returning JSON from the controller is pretty straight forward. Simply return the collection:
public function index() {
$posts = Post::all();
return $posts;
}
Or if you only need to return certain fields, use select()
:
public function index() {
$posts = Post::select(['id', 'subtitle as marketname'])->get();
return $posts;
}
Upvotes: 1