PHP-Laravel-基于多个表单输入的构造请求

时间:2018-08-06 15:52:43

标签: php laravel-5 request

如何设置下面的控制器和视图以将多种形式的输入映射到api参数

我有一个带有支持单个输入条件的表单的视图。控制器随后使用表单输入来查询第三方API并从响应中返回结果。我正在使用Laravel框架,无法让控制器支持多种搜索条件并映射到其他API参数。

控制器(处理来自漫画路线的请求。)

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use GuzzleHttp\Client;
use Cache;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;

class HomeController extends Controller
{
    private $client;

    public function __construct(){

        $ts = time();
        $hash = md5($ts . config('marvel.private_key') . config('marvel.public_key'));

        $this->client = new Client([
            'base_uri' => 'http://gateway.marvel.com/v1/public/',
            'query' => [
                'apikey' => config('marvel.public_key'),
                'ts' => $ts,
                'hash' => $hash
            ]
        ]);

    }

    public function comics(Request $request){

        $search_term = '';
        if($request->has('query')){

            $search_term = $request->input('query');

            $query = $this->client->getConfig('query');
            $query['titleStartsWith'] = $search_term;

            $response = $this->client->get('comics', ['query' => $query]);
            $response = json_decode($response->getBody(), true);

            $comics = $response['data']['results'];

        }else{
            $comics = Cache::get('comics');
            shuffle($comics);
            $comics = array_slice($comics, 0, 20);
        }

        return view('comics', ['comics' => $comics, 'query' => $search_term]);

    }

包含输入表单/呈现的Comcis视图:

    @extends('layouts.default')

@section('content')
<div id="content">
    <h2>Comics</h2>
    <form action="/comics">
        <p>
            <label for="query">Query</label>
            <input type="text" name="query" id="query" value="{{ $query }}">
            <button>Search</button>
        </p>
    </form>

    <div id="comics" class="results">
        @foreach($comics as $com)
        <article class="card">
          <img src="{{ $com['thumbnail']['path'] }}/portrait_incredible.jpg" alt="{{ $com['title'] }} thumbnail">
          <footer>
            <h5>
                <a href="/comics/{{ $com['id'] }}" class="card-title">{{ $com['title'] }}</a>
            </h5>
            <p>
                {{ str_limit($com['description'], 160) }}
            </p>
          </footer>
        </article>
        @endforeach
    </div>
</div>
@stop

1 个答案:

答案 0 :(得分:0)

您可以使用

$input = $request->all()

要从表单中读取所有参数作为数组,然后可以将它们添加到Guzzle请求中。