简体   繁体   中英

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.

UPDATE

This is working for my problem, without perform the query in a foreach: Laravel multiple where clauses in query from given array

My code now is

// grabs all zipcodes matching the distance
$zipcodes = $this->getZipcodes($zipCoordinateId, $distance);

foreach ($zipcodes AS $key=>$val)
{
    $zipcodes[$key] = (array) $val;
}

$codes = array_column($zipcodes, 'zc_zip');

$articles = Article::whereIn('zipcode', $codes)->get();

return view('pages.intern.articles.index', compact('articles'));

UPDATE END

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;
}
}

my view:

@extends('layouts.default')

@section('content')
    <h1>All Articles</h1>
<hr/>

<search>
    {!! Form::open(['url' => 'intern/search']) !!}
        {!! Form::text('zipcode', null, ['class' => 'form-control']) !!}
        {!! Form::select('distance', [
          '5' => '5 km',
          '10' => '10 km',
          '25' => '25 km',
          '50' => '50 km',
          ], null, ['class' => 'form-control']) !!}
        {!! Form::submit('Suchen', ['class' => 'btn btn-success']) !!}
    {!! Form::close() !!}
</search>


@foreach($articles as $article)
    <article>
        <h2>
            <a href="{{ url('/articles', $article->id) }}">{{ $article->name }}</a>
        </h2>

        <div>
            <label>Description:</label>
            <p>{{ $article->description }}</p>
        </div>
        <div>
            <label>ZIPCODE:</label>
            {{ $article->zipcode }}
        </div>
        <div>
            <label>Published:</label>
            {{ $article->published }}
        </div>
        <div>
            <label>Rank:</label>
            {{ $article->rank }}
        </div>
    </article>
    <hr/>
@endforeach
@stop

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

EDIT

When I use

foreach($zipcodes as $key => $value)
        {
            $articles[] = Article::where('zipcode', $value->zc_zip)->get();
        }
        print_r($articles);

With another zipcode in the search and updated zipcodes of my articles, it prints (at the moment, there are three articles in my database, the both first have zipcodes, which are in the range of my new zipcode-search):

Array
(
[0] => Illuminate\Database\Eloquent\Collection Object
    (
        [items:protected] => Array
            (
                [0] => App\Article Object
                    (
                        [fillable:protected] => Array
                            (
                                [0] => name
                                [1] => description
                                [2] => profile
                                [3] => driverlicense
                                [4] => zipcode
                                [5] => published
                                [6] => rank
                                [7] => contact
                                [8] => note
                                [9] => pictures
                                [10] => publisher
                            )

                        [connection:protected] => 
                        [table:protected] => 
                        [primaryKey:protected] => id
                        [perPage:protected] => 15
                        [incrementing] => 1
                        [timestamps] => 1
                        [attributes:protected] => Array
                            (
                                [id] => 5
                                [name] => Test1
                                [description] => Lorem ipsum dolor sit amet, consetetur 
                                [profile] => Lorem ipsum dolor sit amet, consetetur
                                [driverlicense] => yes
                                [published] => no
                                [rank] => 10
                                [contact] => 1
                                [pictures] => 
                                [zipcode] => 89429
                                [note] => 
                                [publisher] => 1
                                [created_at] => 2015-11-04 01:45:18
                                [updated_at] => 2015-11-04 10:07:24
                            )

                        [original:protected] => Array
                            (
                                [id] => 5
                                [name] => Test1
                                [description] => Lorem ipsum dolor sit amet, consetetur
                                [profile] => Lorem ipsum dolor sit amet, consetetur
                                [driverlicense] => yes
                                [published] => no
                                [rank] => 10
                                [contact] => 1
                                [pictures] => 
                                [zipcode] => 89429
                                [note] => 
                                [publisher] => 1
                                [created_at] => 2015-11-04 01:45:18
                                [updated_at] => 2015-11-04 10:07:24
                            )

                        [relations:protected] => Array
                            (
                            )

                        [hidden:protected] => Array
                            (
                            )

                        [visible:protected] => Array
                            (
                            )

                        [appends:protected] => Array
                            (
                            )

                        [guarded:protected] => Array
                            (
                                [0] => *
                            )

                        [dates:protected] => Array
                            (
                            )

                        [dateFormat:protected] => 
                        [casts:protected] => Array
                            (
                            )

                        [touches:protected] => Array
                            (
                            )

                        [observables:protected] => Array
                            (
                            )

                        [with:protected] => Array
                            (
                            )

                        [morphClass:protected] => 
                        [exists] => 1
                        [wasRecentlyCreated] => 
                    )

            )

    )

[1] => Illuminate\Database\Eloquent\Collection Object
    (
        [items:protected] => Array
            (
                [0] => App\Article Object
                    (
                        [fillable:protected] => Array
                            (
                                [0] => name
                                [1] => description
                                [2] => profile
                                [3] => driverlicense
                                [4] => zipcode
                                [5] => published
                                [6] => rank
                                [7] => contact
                                [8] => note
                                [9] => pictures
                                [10] => publisher
                            )

                        [connection:protected] => 
                        [table:protected] => 
                        [primaryKey:protected] => id
                        [perPage:protected] => 15
                        [incrementing] => 1
                        [timestamps] => 1
                        [attributes:protected] => Array
                            (
                                [id] => 6
                                [name] => Test2
                                [description] => Lorem ipsum dolor sit amet, consetetur 
                                [profile] => Lorem ipsum dolor sit amet
                                [driverlicense] => yes
                                [published] => no
                                [rank] => 3
                                [contact] => 1
                                [pictures] => 
                                [zipcode] => 89428
                                [note] => 
                                [publisher] => 1
                                [created_at] => 2015-11-04 01:45:38
                                [updated_at] => 2015-11-04 09:58:01
                            )

                        [original:protected] => Array
                            (
                                [id] => 6
                                [name] => Test2
                                [description] => Lorem ipsum dolor sit amet, consetetur 
                                [profile] => Lorem ipsum dolor sit amet
                                [driverlicense] => yes
                                [published] => no
                                [rank] => 3
                                [contact] => 1
                                [pictures] => 
                                [zipcode] => 89428
                                [note] => 
                                [publisher] => 1
                                [created_at] => 2015-11-04 01:45:38
                                [updated_at] => 2015-11-04 09:58:01
                            )

                        [relations:protected] => Array
                            (
                            )

                        [hidden:protected] => Array
                            (
                            )

                        [visible:protected] => Array
                            (
                            )

                        [appends:protected] => Array
                            (
                            )

                        [guarded:protected] => Array
                            (
                                [0] => *
                            )

                        [dates:protected] => Array
                            (
                            )

                        [dateFormat:protected] => 
                        [casts:protected] => Array
                            (
                            )

                        [touches:protected] => Array
                            (
                            )

                        [observables:protected] => Array
                            (
                            )

                        [with:protected] => Array
                            (
                            )

                        [morphClass:protected] => 
                        [exists] => 1
                        [wasRecentlyCreated] => 
                    )

            )

    )

[2] => Illuminate\Database\Eloquent\Collection Object
    (
        [items:protected] => Array
            (
            )

    )

)

EDIT 2

I print_r the articles from $articles = Article::all();, which uses the same return view('pages.articles', compact('articles')); and displays on the same site:

Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
    (
        [0] => App\Article Object
            (
                [fillable:protected] => Array
                    (
                        ...
                    )

                [connection:protected] => 
                [table:protected] => 
                [primaryKey:protected] => id
                [perPage:protected] => 15
                [incrementing] => 1
                [timestamps] => 1
                [attributes:protected] => Array
                    (
                        ...
                    )

                [original:protected] => Array
                    (
                        ...
                    )

                [relations:protected] => Array
                    (
                    )

                [hidden:protected] => Array
                    (
                    )

                [visible:protected] => Array
                    (
                    )

                [appends:protected] => Array
                    (
                    )

                [guarded:protected] => Array
                    (
                        [0] => *
                    )

                [dates:protected] => Array
                    (
                    )

                [dateFormat:protected] => 
                [casts:protected] => Array
                    (
                    )

                [touches:protected] => Array
                    (
                    )

                [observables:protected] => Array
                    (
                    )

                [with:protected] => Array
                    (
                    )

                [morphClass:protected] => 
                [exists] => 1
                [wasRecentlyCreated] => 
            )

        [1] => App\Article Object
            (
                [fillable:protected] => Array
                    (
                        ..
                    )

                [connection:protected] => 
                [table:protected] => 
                [primaryKey:protected] => id
                [perPage:protected] => 15
                [incrementing] => 1
                [timestamps] => 1
                [attributes:protected] => Array
                    (
                        ...
                    )

                [original:protected] => Array
                    (
                        ..
                    )

                [relations:protected] => Array
                    (
                    )

                [hidden:protected] => Array
                    (
                    )

                [visible:protected] => Array
                    (
                    )

                [appends:protected] => Array
                    (
                    )

                [guarded:protected] => Array
                    (
                        [0] => *
                    )

                [dates:protected] => Array
                    (
                    )

                [dateFormat:protected] => 
                [casts:protected] => Array
                    (
                    )

                [touches:protected] => Array
                    (
                    )

                [observables:protected] => Array
                    (
                    )

                [with:protected] => Array
                    (
                    )

                [morphClass:protected] => 
                [exists] => 1
                [wasRecentlyCreated] => 
            )

        [2] => App\Article Object
            (
                [fillable:protected] => Array
                    (
                        ..
                    )

                [connection:protected] => 
                [table:protected] => 
                [primaryKey:protected] => id
                [perPage:protected] => 15
                [incrementing] => 1
                [timestamps] => 1
                [attributes:protected] => Array
                    (..
                    )

                [original:protected] => Array
                    (
                        ..
                    )

                [relations:protected] => Array
                    (
                    )

                [hidden:protected] => Array
                    (
                    )

                [visible:protected] => Array
                    (
                    )

                [appends:protected] => Array
                    (
                    )

                [guarded:protected] => Array
                    (
                        [0] => *
                    )

                [dates:protected] => Array
                    (
                    )

                [dateFormat:protected] => 
                [casts:protected] => Array
                    (
                    )

                [touches:protected] => Array
                    (
                    )

                [observables:protected] => Array
                    (
                    )

                [with:protected] => Array
                    (
                    )

                [morphClass:protected] => 
                [exists] => 1
                [wasRecentlyCreated] => 
            )

    )

)

So the output from my print_r($articles) should be something like this.

EDIT 3

My current foreach is:

foreach($zipcodes as $key => $value)
        {
            //$code = $zipcodes[0]->zc_zip; // working, prints out one article
            //$article = Article::where('zipcode', $code)->get();
            $article = Article::where('zipcode', $value->zc_zip)->get();
            //print_r($article);
        }
        print_r($article);

You could try this:

foreach($zipcodes as $key => $value)
{
    $articles[] = Article::where('zipcode', $value->zc_zip)->get();
}
return view('pages.articles', compact('articles'));

View:

@foreach($articles as $article)
<article>
    <h2>
        <a href="{!! url('/articles', $article->id) !!}">{!! $article->name !!}</a>
    </h2>

    <div>
        <label>Description:</label>
        <p>{!! $article->description !!}</p>
    </div>
    <div>
        <label>ZIPCODE:</label>
        {!! $article->zipcode !!}
    </div>
    <div>
        <label>Published:</label>
        {!! $article->published !!}
    </div>
    <div>
        <label>Rank:</label>
        {!! $article->rank !!}
    </div>
</article>
<hr/>
@endforeach

You have declared $articles = array(); and then you're passing $article (without the s ) to compact function, that is why you get an undefined variable in your view, also when you are looping in the foreach you must do it like this :

@foreach($articles as $article)
....
@endforeach

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM