Laravel: Embedding PHP Code in Blades
Submitted by nurhodelta_17 on Tuesday, November 21, 2017 - 20:45.
Getting Started
In this tutorial I'm going to limit the number of items shown per row using PHP so I'm going to embed the PHP code with the foreach. Also, I'll be using the upload project from the previous tutorial, Laravel Multiple File Upload, wherein I'm going to show the uploaded images.Embedding our PHP Code
Next, we're going to edit the contents of upload.blade.php located in resources/views folder with the ff:- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Laravel: Embedding PHP Code in Blades</title>
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
- </head>
- <body>
- <div class="container">
- <h1 class="page-header text-center">Embedding PHP Code in Blades</h1>
- <div class="row">
- <div class="col-md-4">
- <div class="well">
- <h2 class="text-center">Upload Form</h2>
- <form method="POST" action="{{ route('upload.file') }}" enctype="multipart/form-data">
- {{ csrf_field() }}
- <input type="file" name="file[]" multiple><br>
- <button type="submit" class="btn btn-primary">Upload</button>
- </form>
- </div>
- <div style="margin-top:20px;">
- @foreach($errors->all() as $error)
- <div class="alert alert-danger text-center">
- {{$error}}
- </div>
- @endforeach
- @endif
- @if(session('success'))
- <div class="alert alert-success text-center">
- {{session('success')}}
- </div>
- @endif
- </div>
- </div>
- <div class="col-md-8">
- <h2>Uploaded Images</h2>
- @php
- $inc=3;
- @endphp
- @foreach($files as $file)
- @php
- $inc = ($inc == 3) ? 1 : $inc+1;
- if($inc == 1) echo "<div class='row'>";
- @endphp
- <div class="col-md-4">
- <img src="{{ $file->location }}" class="thumbnail" style="height:200px; width:100%">
- </div>
- @php
- if($inc == 3) echo "</div>";
- @endphp
- @endforeach
- @php
- if($inc == 1) echo "<div class='col-md-4'></div><div class='col-md-4'></div></div>";
- if($inc == 2) echo "<div class='col-md-4'></div></div>";
- @endphp
- </div>
- </div>
- </div>
- </body>
- </html>
Running our Project
You can test our code by deleting all existing data in our upload database and upload image files only. Run our project by typing upload.dev in your web browser. That ends this tutorial. Happy Coding :)Add new comment
- 283 views