0

I am having trouble displaying data in the View from arrays in my DB, I have tried multiple methods to no avail. I need to display all of the results in the View from both arrays in the DB (Name and Url) - I have tried for loops although I can't seem to target the data correctly. I also do not know where I am going wrong in my code. I am new to Laravel.

Any help would be appreciated.

DB Instance:

local.INFO: array (
  '_token' => 'kwsRPOc9YH4pjvmAVsibJULiMUItzZu2BEWimJy6',
  'name' => 
  array (
    0 => 'linkOne',
    1 => 'linkTwo',
  ),
  'url' => 
  array (
    0 => 'urlOne',
    1 => 'urlTwo',
  ),
)

Controller:

public function addMorePost(TagList $tagslist, Request $request)
{

  Log::info($request);

  foreach($request as $key => $value) {

    TagList::create([
      'name[]'=>[$value],
      'url[]'=>[$value]
    ]);
  }

  $tagslist = \App\Taglist::all();
  return view('addMore', ['tagslist' => $tagslist]);

}

View:

@foreach ($tagslist as $tag)

  <div>
    <p class="name">{{ $tag->name }}</p>
    <p class="url">{{ $tag->url }}</p>
  </div>

  @endforeach
1
  • If both your name field and url field contain arrays, you will need to iterate both of them separately. Why don't you keep one multidimensional array instead of two? That way you can ensure that both arrays will have same number of items. Commented Nov 12, 2018 at 12:22

1 Answer 1

1

As your question is tagged laravel, you can use a collection with combine https://laravel.com/docs/5.7/collections#method-combine

collect($name)->combine($url);

will result in

linkOne => urlOne,
linkTwo => urlTwo,

if you want you could go 1 step further (I see no need) to achieve exactly what is in your view at the moment.

$tags = collect($name)->combine($url)->map(function ($item, $key) {
    $tag = new \stdClass();
    $tag->{'name'} = $key;
    $tag->{'url'} = $item;
    return $tag;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Brilliant. Thank you very much!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.