mardi 3 novembre 2015

Laravel 5 add results from query in a foreach to array

I have a problem in my Laravel 5 application. My controller-method contains a foreach, which should iterate over a previous Eloquent-result-array (it is named $zipcodes). So each zipcode is used to fill a query, which result returns an Article-object (named $article). Every end of iteration it should add the Article-result to an array ($articles), which is used at the end of my method to display the Articles on my page. Maybe there is a better option for the performing of the Article-query, not every iteration, but I don't know how. My SearchController:

<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class SearchController extends Controller
{
public function getSearch(Request $request)
{
    if(($request->has('zipcode'))) {
        $zipcode = $request->input('zipcode');
        $distance = $request->input('distance');

        $zipCoordinateId = $this->getZipCoordindateId($zipcode);
        $zipcodes = $this->getZipcodes($zipCoordinateId, $distance);

        $articles = array();

        foreach($zipcodes as $value) {
            //$zipcode = $zipcodes[0]->zc_zip; // this is working
            $zipcode = $value->zc_zip;

            $article = Article::where('zipcode', $zipcode)->get();


           // add the $article each iteration to $articles
        }

        return view('pages.articles', compact('articles'));
    } else {
        return redirect('/articles');
    }
}

public function getZipCoordindateId($value) {
    $result = DB::table('zip_coordinates')
            ->where('zc_zip', '=' , $value)
            ->orWhere('zc_location_name', 'LIKE', $value)
            ->pluck('zc_id');
    return $result;
}

public function getZipcodes($id, $distance) {

    $result = DB::select(
        DB::raw("
            SELECT dest.zc_zip,
                ACOS(
                    SIN(RADIANS(src.zc_lat)) * SIN(RADIANS(dest.zc_lat))
                    + COS(RADIANS(src.zc_lat)) * COS(RADIANS(dest.zc_lat))
                    * COS(RADIANS(src.zc_lon) - RADIANS(dest.zc_lon))
                ) * 6380 AS distance
            FROM zip_coordinates AS dest
            CROSS JOIN zip_coordinates AS src
            WHERE src.zc_id = :id
            HAVING distance < :distance
            ORDER BY distance"), array('id' => $id, 'distance' => $distance));

    return $result;
}
}

Hope you can help me, thank you in advance. quantatheist



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire