Friday 10 April 2015

Condition and loops in laravel

This post is about constructing loops and conditions in laravel using Blade template.So lets get started.
Open the routes.php file and create an array.What we will do here is create an array an add some conditions and loops to it so that use of each conditions becomes more clear.We will be passing the array from routes.php to views if you don't know how to do this I suggest you to read Routing in Laravel with Route Parameters . So lets get started
Open routes.php and type in the following code



1
2
3
4
Route::get('fruits',function(){
 $fruitlist = array('Apple','Mango','Banana');
 return View::make('fruits')->withFruits($fruitlist);
});

What we have done is just created an array of fruits and a route to fruit.blade.php using Laravel Magic method.Now we can access the fruits array in the fruit view.
fruits.blade.php file


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<!DOCTYPE html>
<html>
<head>
 <title>Fruits page</title>
</head>
<body>
 
{{ $fruits[0] }} <br/>
{{ $fruits[1] }} <br/>
{{ $fruits[2] }} <br/><br/><br/>
 
 Using condition statement 
 <br/>
 @if(count($fruits)>0)
 Fruits array is not empty <br/>
 @endif

@if(count($fruits)>3)
 Fruits array have more than 3 fruits <br/>
@elseif(count($fruits)<=3)
 Fruits array may have 3 fruits or less <br/>
@endif
<br/>
<br/>

Using for loop <br/>
@for($i = 0 ;$i < count($fruits);$i++ )
{{$fruits[$i]}} <br/> 
@endfor
<br/>
<br/>

Using foreach loop<br/>
@foreach($fruits as $fruit)
Fruit is {{$fruit}}<br/>
@endforeach
</body>
</html>


We have demonstrated a few of  basic conditions and loops in this example the rest can be coded in the same manner.All conditions and loops that are valid in PHP are valid in laravel,You can make use of any of those as per your requirement.
The output


1 comment:

  1. Good web development company New York are those who never charge anything extra than the agreed amount of the order and always cares more about delivering perfect work within the deadline. They will provide project estimates timelines upfront to their clients; therefore never pay any hidden fee to the companies who do not finish your site on time and charge you an extra fee after the contract. The professional ethics matter while choosing a web design company; the professional companies are easy to work with who reply to your emails, chats, and queries early.

    ReplyDelete