iMarkDesigns
iMarkDesigns

Reputation: 1262

Proper use of Array and Foreach at Laravel

I don't understand how to convert my PHP array into Laravel, I am new to Laravel and can't even find exact format to follow it. I would like to use it on my blade file. Here's my php code.

$properties = array('office', 'retail');
foreach ($properties as $property) :
  echo $property;
endforeach;

And i did my best but no luck to output the correct format from Laravel

$properties = array('office', 'retail')
@foreach ($properties as $property)
  {{ $property }}
@endforeach

Thanks for the clarification.

Upvotes: 1

Views: 655

Answers (3)

AnkiiG
AnkiiG

Reputation: 3488

Try as below :

 <?php $properties = array('office', 'retail'); ?>
 @foreach ($properties as $property)
    {{ $property }}
 @endforeach

Upvotes: 2

hhsadiq
hhsadiq

Reputation: 2943

Its important to first understand the working of blade control structures. Laravel 5 provides many control structures for working with blade files.

Echoing Data

Hello, {{ $name }}.

The current UNIX timestamp is {{ time() }}.

Echoing Data After Checking For Existence

Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. Basically, you want to do this:

{{ isset($name) ? $name : 'Default' }}

However, instead of writing a ternary statement, Blade allows you to use the following convenient short-cut:

{{ $name or 'Default' }}

Displaying Raw Text With Curly Braces

If you need to display a string that is wrapped in curly braces, you may escape the Blade behavior by prefixing your text with an @ symbol:

@{{ This will not be processed by Blade }}

If you don't want the data to be escaped, you may use the following syntax:

Hello, {!! $name !!}.

Docs help

For more detail you can read the laravel docs about Laravel Templates

Underlying Concepts

So basically Laravel gives you a pretty and safe way of displaying the dynamic data. The blade code is parsed by the Laravel templating engine and replaced with relevant PHP code. So if you wrapping the blade code in <?php ?> the Laravel will be unable to parse it and will crash.

Analogy For Wrong Code

Its like you have wrapped the HTML code in <?php ?> and expecting the HTML engine will somehow render it. Hope this will clarify your underlying blade concepts.

Upvotes: 1

Sulthan Allaudeen
Sulthan Allaudeen

Reputation: 11310

Your code is perfect and it should work if your page is a blade i.e., Your file name should something like somepage.blade.php

You shall also add another braces

@foreach ($properties as $property)
  {{{ $property }}}
@endforeach

Update :

You should not use {{ or {{{ inside your php code !!!

You shall simply have like this

<?php
$properties = array('office', 'retail')
?>
@foreach ($properties as $property)
  {{{ $property }}}
@endforeach

Upvotes: 2

Related Questions