Home > Software engineering >  php recordset in Laravel @foreach alternative
php recordset in Laravel @foreach alternative

Time:11-08

Can you tell me how to do this properly please?

I'm using Laravel 8. Passing a recordset to a page which I deal with using a foreach loop later in the page. How do I get data out of it without a forloop? I've bodged it using

@foreach ($sites as $site)
     <img src="{{$site->url}}" alt="Pic" id="bg-img" onclick = fill() />
@break
@endforeach

I've used a foreach loop as it works later in the page.

Yes it works but I'd like to know the proper way.

I've also tried:

{{$site->url}}
{{$sites->url}}
$sites['url']

I'm new to Laravel and rubbish with array type things in php.

Thank you

Am I allowed to ask this improvement type question?

CodePudding user response:

I just explained some of the statements you made.

For example, you have data like this:

----------------------------
| id | url                 |
----------------------------
| 1  | http://domain-1.tld |
| 2  | http://domain-2.tld |
| 3  | http://domain-3.tld |
| 4  | http://domain-4.tld |
| 5  | http://domain-5.tld |
----------------------------

For example, you have query :

$sites = Site::get();

The get method returns an Illuminate\Support\Collection instance containing the results of the query where each result is an instance of the PHP stdClass object. You may access each column's value by accessing the column as a property of the object:

@foreach ($sites as $site)
    {{ $site->url }}
@endforeach
  • If you use $sites->url, it will be an error, because there is no object :

    Property [url] does not exist on this collection instance.
    
  • If you use $sites['url'], it will also be an error.

  • You can use $site['url'], when you convert collection to array :

    $sites = Site::get()->toArray();
    

@break

When you use break, it will ends execution of the current for, foreach, while, do-while or switch structure.

From your code, it will take the first iteration only.

@foreach ($sites as $site)
    @break // stop
@endforeach

How do I get data out of it without a forloop?

Looks like you want to retrieve single row. You can use first() :

$site = Site::first();
$site->url;

CodePudding user response:

// if you want html break between images then use this.

use echo '
';

otherswise use directly with php tag

break;

  • Related