I have a blade where I'm printing the content of a table.
For some columns I need to add the CSS class according the value I'm printing.
E.g. if it's "OK", add class Green, otherwise class red.
Of course the logic will be more complex, but the point is that all the logic will be related to the style.
Which one is the best recommended place to save this type of function/method?
Do I need to create a Model?
** UPDATE **
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Last Checked </th>
<th> Status </th>
</tr>
</thead>
<tbody>
#foreach ($users as $u)
<tr>
<td> {{ $u->id }}</td>
<td> {{ $u->name }}</td>
<td> {{ $u->last_login }}</td>
<td> {!! statusWrapper( $u->status ) !!}</td>
</tr>
#endforeach
</tbody>
</table>
"statusWrapper" is the function that I'd like to call to decorate the Status value.
So the status is a number, and the output will be something like <span class="..."> .... </span>
If status should include HTML like showing different colors I recommend you use #include
// resources/views/statusWrapper
#if($status == 'good')
<span style="color: green;">thats really good</span>
#else
<span style="color: red;">not good</span>
#endif
and then in your table view
#foreach ($users as $u)
<tr>
<td> {{ $u->id }}</td>
<td> {{ $u->name }}</td>
<td> {{ $u->last_login }}</td>
<td>
#include('statusWrapper', ['status' => $u->status])
</td>
</tr>
#endforeach
You could also look at extending blade: https://laravel.com/docs/5.5/blade#extending-blade
But I will not recommend you to put HTML in your PHP code as it's easier to keep your HTML in your view files for future edits.
I recommend you what I always do myself. You don't need to make a model, you just have to make a helper file and write all your custom functions in it. For example you can make a file named helper.php in app/Http/Helpers/ path. Then you have to make your project aware of this file. To do that you just have to add it in your composer.json file in autoload -> files object like this:
"autoload": {
"files":[
"app/Http/Helpers/helper.php"
]
}
After this just run command composer dump-autoload. Now you can access to your custom functions which are in you helper.php file from anywhere.
app/providers/AppServiceProvider.php (You can create a different Service Provider, if you wish)
use Illuminate\Support\Facades\Blade;
...
class AppServiceProvider extends ServiceProvider
{
...
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
Blade::directive('statusWrapper', function ($status) {
return "<?php echo App\ViewComponents\StatusWrapperComponent::statusWrapper( $status ); ?>";
});
}
}
app/ViewComponents/StatusWrapperComponent.php
namespace App\ViewComponents;
class StatusWrapperComponent {
public static function statusWrapper ($status) {
if($status == 'good')
echo '<span style="color: green;">thats really good</span>';
else
echo '<span style="color: red;">not good</span>';
}
}
resources/views/yourview.blade.php
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Last Checked </th>
<th> Status </th>
</tr>
</thead>
<tbody>
#foreach ($users as $u)
<tr>
<td> {{ $u->id }}</td>
<td> {{ $u->name }}</td>
<td> {{ $u->last_login }}</td>
<td> #statusWrapper($u->status) </td>
</tr>
#endforeach
</tbody>
</table>
If you're planning to use the function in multiple blade templates, then Tohid's answer is the best.
If you just need the function in a single template, you can define it directly in the .blade.php file like this:
#php
if ( !function_exists( 'mytemplatefunction' ) ) {
function mytemplatefunction( $param ) {
return $param . " World";
}
}
#endphp
Then in you can call the function from within the same template:
<p>{{ mytemplatefunction("Hello") }}</p>
The conditional function definition is needed if you include the blade template multiple times in the same session.
Related
I would like to create a table and populate it with data using vue.js and v-for but I don`t know how to access the nested JSON file.
If I simply call {{items}} the data is presented but there is no way i manage to filter it
here is my code:
<template>
<div id="app">
<thead>
</thead>
<tbody>
<table>
<thead>
<tr>
<th>id</th>
<th>press</th>
<th>date</th>
</tr>
</thead>
<tbody>
<tr v-for="item in items" :key="item.id">
<td>{{ item.id }}</td>
<td>{{ item.results.downloadable.document_en }}</td>
<td>{{ item.}}</td>
</tr>
</tbody>
</table>
</tbody>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
items:[]
}
},
created() {
axios.get(`https://zbeta2.mykuwaitnet.net/backend/en/api/v2/media-center/press-release/?page_size=61&type=5`)
.then(response => {
this.items = response.data
})
}
}
</script>
Based on the result of your endpoint you should change your assignment of items to
.then(response => {
this.items = response.data.results
})
And your loop to
<tr v-for="item in items" :key="item.id">
<td>{{ item.id }}</td>
<!-- as downloadable is an array, see update below etc. -->
</tr>
But be aware - if you assign the data.results directly you will lose the so called "paginator" information that also contains the link to load more.
So another option would be to assign
this.items = response.data
HOWEVER, be aware that you should then define items in your data as null or empty object (not array, as this would be false)
And then change your loop to something like this (it's now looping in item.results)
<tbody v-if="items && items.results">
<tr v-for="item in items.results" :key="item.id">
<td>{{ item.id }}</td>
<!-- as downloadable is an array - see Update below etc. -->
</tr>
</tbody>
This approach would allow you to show the total count via items.count for example
UPDATE:
Actually downloadable is an array! I can only assume what you actually want to achieve to here. I've created a jsfiddle to showcase it: https://jsfiddle.net/v73xe4m5/1/
The main thing you probably want to do is filter the entry to only show entries where downloadable contains a document_en.
<tr v-for="item in items.results" :key="item.id">
<td>{{ item.id }}</td>
<td>
<div class="downloads">
<span
v-for="downloadable in item.downloadable.filter(d => !!d.document_en)"
:key="downloadable.id"
>{{ downloadable.document_en.file }}</span>
</div>
</td>
</tr>
I'm not familiar with that endpoint / api - so I don't know if it might return more than one relevant document per item.
As you can see I used a second v-for loop inside the <td> in order to go through all downloadable entries. Before doing so, they are filtered, so only entries that actually have a document_en value are shown. You can adapt this as you want.
Hope that helps!
this is the correct form to get the array from the json and save to this.items
this.items = response.data.results
I encourage you to always console.log(response) after api call , and access data according to the structure of the api results
I'm new ton Laravel (also to StackOverflow), and I'm trying to show data in my home.blade.php table from PhpMyAdmin using a foreach loop. However, it's not working correctly, and I can't figure out where the problem is. I have other tables working with foreach, and I've followed the same steps with this table.
User Model
protected $table = 'users';
protected $fillable = ['id','name','edad','direccion_personal','celular','foto','email','direccion_sucursal_id'];
UserController
public function index()
{
$Usuarios = User::all();
$array = ['usuarios' => $Usuarios];
return view('home')->with($array);
}
Finally, here's my tbody:
<tbody>
#foreach ($usuarios as $Usuarios)
<div>
<tr>
<th scope="row" style="text-align:center;">{{ $Usuarios->id }}</th>
<td style="text-align:center;">{{ $Usuarios->nombre }}</td>
.
.
.
</tr>
</div>
</tbody>
#endforeach
Why the array?
public function index(){
$usuarios = User::all();
return view('home', compact('usuarios'));
}
Then:
<tbody>
#foreach ($usuarios as $us)
<div>
<tr>
<th scope="row" style="text-align:center;">{{$us->id}}</th>
<td style="text-align:center;">{{$us->nombre}}</td>
.
.
.
</tr>
</div>
#endforeach
</tbody>
I see you're having troubles with the foreach loop. is not working correctly... but, I'm not sure what kind of problem is... if my answer does not work for you, please update your question so you can get more help
I see you close your inside the foreach loop.
That way you will end with lots of closing tags with just one opening...
Try moving that close tag outside the loop
<tbody>
#foreach ($usuarios as $Usuarios)
<div>
<tr>
<th scope="row" style="text-align:center;">{{$Usuarios->id}}</th>
<td style="text-align:center;">{{$Usuarios->nombre}}</td>
.
.
.
</tr>
</div>
#endforeach
</tbody>
Your foreach closes outside the </tbody> tag, and opens inside it. Your table body is thus closed after the first iteration of the loop, and never opened again, so with each iteration you now have an additional </tbody> line. This is invalid markup, and will break your site's output.
I try to create a table that containt checkbox using laravel blade .
But checkbox does not appear in the table.
this is my code:
#section('content')
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>Survey</th>
<th>Date</th>
<th>Published</th>
<th>Creator</th>
<th>seen</th>
</tr>
</thead>
<tbody>
#foreach($surveys as $survey)
<tr {!! !$survey->seen && session('statut') == 'admin'? 'class="warning"' : '' !!}>
<td>{{$survey->title}}</td>
<td>{{$survey->created_at->todatestring()}}</td>
<td>{!! Form::checkbox('active', $survey->id, $survey->active) !!}</td>
#foreach($users as $user)
#if($user->id == $survey->user_id)
<td>
{{$user->name}}
</td>
#endif
#endforeach
<td>{!! Form::checkbox('seen', $survey->id, $survey->seen) !!}</td>
<td><button type="button" class="btn btn-info">Detail</button></td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
help me please!thank you in advance
Please use in this way.
{{ Form::checkbox('agree', 'yes') }}
Refer to this URL
I've tried your code and the checkbox works fine without problem as long as you already done all of this things correctly.
Install & setup Laravel Collective (https://laravelcollective.com/docs/master/html)
$surveys already sent from your controller with its data
$survey->seen contains boolean value (true/false)
I want to display the database values depending on the particular ID. I pass that id in the URL, and it redirects to another page with ID. In that page I have to display that particular user's records.
Here is the controller function:
public function consultants()
{
return view('Hr/view-request-candidates', [
'consultant' => HrRequestConsultant::all(),
]);
}
Route:
Route::get(
'/view-request-candidates/{hr_request_id}',
'Hr\HrDashboardController#consultants'
);
URL:
CANDIDATES
View:
<div class="col-md-12">
<table class="table table-striped">
<tbody>
<tr>
<th>Hr Request ID</th>
<th>Consultant ID</th>
<th>No Of Candidates</th>
<th>Actions</th>
</tr>
#foreach($consultant as $row)
<tr>
<td>{{$row->hr_request_id}}</td>
<td>{{$row->consultant_id}}</td>
<td>{{30}}</td>
<td>
<a href="/view-hr-candidates" class="btn btn-primary">View</button>
</td>
</tr>
#endforeach
How can I do this?
Routes::
Route::get('home','HrDashboardController#home');
Route::get('view-hr-candidates/{hr_request_id}','HrDashboardController#consultants');
Controller::
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\HrRequestConsultant;
use DB;
class HrDashboardController extends Controller
{
public function home(){
$home = HrRequestConsultant::select('id','hr_request_id','consultant_id')->get();
return view('home')->with('home', $home);
//Its View: home.blade.php file
}
public function consultants($id){
$result = HrRequestConsultant::select('id','hr_request_id','consultant_id')->where('hr_request_id',$id)->first();
return $returnview = view('Hr.view-request-candidates')->with('result', $result);
// Its view-request-candidates.blade.php file InSide the Hr Dir.
}
}
home.blade.php::
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md"> View Details </div>
<div class="col-md-12">
<table border="1" style='color: black'>
<tr>
<th>Hr Request ID</th>
<th>Consultant ID</th>
<th>No Of Candidates</th>
<th>Actions</th>
</tr>
#foreach ($home as $data){
<tr>
<td> {{ $data['hr_request_id'] }} </td>
<td> {{ $data['consultant_id'] }} </td>
<td> 30 </td>
<td> View </td>
</tr>
#endforeach
</table>
</div>
</div>
</div>
</body>
view-request-candidates.blade.php
<h1> Hello .. This Is Request Id: {{ $result['hr_request_id'] }} </h1>
<br>
<h1> Hello .. This Is Consultant Id: {{ $result['consultant_id'] }} </h1>
To get the single record use the find method instead of all:
public function consultants($id)
{
return view('Hr/view-request-candidates', [
'consultant' => HrRequestConsultant::find($id),
]);
}
It is best practice to name the route and use name wherever you need that route. So change the route like this :
Route::get(
'/view-request-candidates/{hr_request_id}',
'Hr\HrDashboardController#consultants')->name('view.consultant');
Remove the foreach loop from your view and change the route to named route:
<div class="col-md-12">
<table class="table table-striped">
<tbody>
<tr>
<th>Hr Request ID</th>
<th>Consultant ID</th>
<th>No Of Candidates</th>
<th>Actions</th>
</tr>
<tr>
<td>{{$consultant->hr_request_id}}</td>
<td>{{$consultant->consultant_id}}</td>
<td>{{30}}</td>
<td>
<a href="{{ route('view.consultant', ['hr_request_id' => $consultant->hr_request_id]) }}" class="btn btn-primary">View</button>
</td>
</tr>
$matrix = \Matrix::instance();
$cal = $matrix->calendar('2014-06', 1);
I can not work out how to use data in $cal & get it to display in view
The calendar() method returns an array of weeks.
Here's a basic example:
index.php
$f3=require('lib/base.php');
$f3->route('GET /cal/#year/#month',function($f3,$params){
$f3->cal=Matrix::instance()->calendar($params['year'].'-'.$params['month'],1);
$f3->title=date('F Y',mktime(0,0,0,$params['month'],1,$params['year']));
echo Template::instance()->render('cal.html');
});
$f3->run();
cal.html
<h1>{{ #title }}</h1>
<table>
<thead>
<tr>
<th>Mo</th>
<th>Tu</th>
<th>We</th>
<th>Th</th>
<th>Fr</th>
<th>Sa</th>
<th>Su</th>
</tr>
</thead>
<tbody>
<repeat group="#cal" value="#week">
<tr>
<loop from="$d=0" to="$d<7" step="$d++">
<td>{{ ##week[ #d ] }}</td>
</loop>
</tr>
</repeat>
</tbody>
</table>
Now GET /cal/2014/06 should return something like: