Laravel blade, recursive view with php translated to blade - laravel

I have this recursive view with php, which is plain wrong so I have to translate this to blade, for recursive call for a view.
My php recursive code in (comments.blade.php):
<?php
tree($Comments, 0, 0);
$var = -1;
function tree($Comments, $parent_id = 0, $level=0, $c=0) {
global $var;
foreach($Comments as $Comment) {
if($Comment['parent_id'] == $parent_id) {
If ($level > $var) $var++; else {
for ($i = $var-$level+1; $i>0; $i--) { if ($c < 0) echo '</div> </div>'; else $c--; };
$var=$level;
};
echo '<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="..." alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">Media heading</h4>';
tree($Comments, $Comment['id'], $level+1,$c);
}
};
};
?>
And that's what I am looking for(in comments.blade.php:
<div>
#include('recursive', ['comments' => $comments, 'parent_id' => 0, 'level' => 0, 'c' => 0])
</div>
The thing is I don't know how to translate all that variables in first snippet of code into blade, so to create Recursive.blade.php:
Edit 1:
Guys please help me, I worked 2 days on this damn algorithm and I am stuck once again in a problem even bigger then it was 2 days ago :(
For some people that doesn't understand why I am sticking with that code is because that code above is the algorithm for making the threaded comments like that on reddit, in the algorithm there is 2x echo, and a media class echo.
If i put 2x after the media class on 2 comments in a row, the next one comment will create with first one, comments with same parent_id, this means they are childs that belong to the same comment(parent before them), If the 2x div are not put then this means the next one comment after first is the child of the first and so on. This is my algorithm, i am doing this to translate to blade because I have some cheeky votes buttons which uses routes that i will integrate into recursive design, that's why i want to be translate to blade, but i don't know how. :(

Why would you call the recursively for generating the view, you can make an file name comment.blade.php and run a loop inside main blade file which will include the comment.blade.php and pass the comment object or array and then the comment.blade.php file will user the properties of that $comment object or array.
For example:
$Comments = [
[
'body' => 'First comment',
'name' => 'First Commentator'
],
[
'body' => 'Second comment',
'name' => 'Second Commentator'
],
[
'body' => 'Third comment',
'name' => 'Third Commentator'
],
[
'body' => 'Fourth comment',
'name' => 'Fourth Commentator'
],
[
'body' => 'Fifth comment',
'name' => 'Fifth Commentator'
],
[
'body' => 'Sixth comment',
'name' => 'Sixth Commentator'
],
];
and in your main blade file that can be index.blade.php or any other
#foreach($Comments as $Comment)
#include('comment',['comment'=>$comment])
#endforeach
comment.blade.php file would have
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object" src="..." alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">Media heading</h4>
</div>
</div>

There is a automatic tool for get this job done. check out PHP2Blade
you can convert multiple files to blade syntax by runnig this command.
php php2blade <files directory> <optional output directory>

Related

Codeigniter 4 - Apply validation rules without making the fields required for URL

I want to apply validation rules only for the input fields that are not empty (not required) for the URL
For example,
If I submit a form and the input is empty, I got a validation error "Instagram Link must be valid URL.", However, I want it without requiring,
and if the input is not empty, I want to apply the rule "valid_url"
How can we fix it?
if (!$this->validate([
'instagram' => [
'rules' => 'valid_url',
'errors' => [
'valid_url' => 'Instagram Link must be valid url.',
],
],
])){
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
I tried with a permit_link rule, but if I submit it (with an input value like 'mylink' (which is not a valid_url)), it will accept it, but it should not.
Please check the following images and the code:
A form HTML
Result after clicking on edit button
<?= form_open('/settings/edit/1', ['id' => 'setting-form']); ?>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<?= form_label('Instagram'); ?>
<?= form_input(['name' => 'instagram', 'class' => 'form-control', 'id' => 'instagram', 'placeholder' => 'Enter instagram link', 'value' => old('instagram', $setting->instagram)]); ?>
</div>
</div>
</div>
<button type="submit" class="btn btn-dark">Edit</button>
<?= form_close(); ?>
public function edit($id)
{
if (!$this->validate([
'instagram' => [
'rules' => 'permit_empty|valid_url',
'errors' => [
'valid_url' => 'Instagram Link must be valid url.',
],
],
])) {
return redirect()->back()->withInput()->with('errors', $this->validator->getErrors());
}
die('submitted');
}
It should display "Instagram Link must be valid url" and not "submitted",
first
Use separate variable $rules like this :
$rules = ['data' => 'require']
Then
check if $this->request->getVar("instagram"); is empty / is true or etc.. then set it on the $rules
finally
Do Something like this :
$rules = ['extra_data' => 'require'];
if(!empty($this->request->getVar("instagram"))
$rules["instagram"] = "valid_url";
if ($this->validate(rules){
//do something ...
}else {
//do something ...
}
I just noticed that the following examples:
"mylink", "mylink.com", "https://www.mylink.com"
will consider correct for the rule valid_url in Codeigniter (No errors),
While: "https:://www.mylink.com", "mylink#" will apply the validation and the error is applied.

Lavachart - can not set property of "style" of null

I just started using this library in laravel but it seems that it's not working.
This is the controller's code used:
$entries = \Lava::DataTable();
$query = Survey::select('country AS 0', \DB::raw('count(country) AS entries'))->groupBy('country')->get()->toArray();
$data = [];
foreach ($query as $q) {
$data[] = [$q[0], $q['entries']];
}
$entries->addStringColumn('Country')
->addNumberColumn('Popularity')
->addRows($data);
\Lava::GeoChart('Popularity', $entries);
return view('dashboard.homepage', ['colorsNum' => $colorsNum]);
This is my blade file:
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-body">
<div id="pop-div"></div>
#geochart('Popularity', 'pop-div')
</div>
</div>
</div>
</div>
enter image description here
It's showing this red error: Cannot read property 'style' of null
I don't know what's going wrong so please if you can help me, your help is much appreciated.
I resolved the by passing the third parameter options
$lava->GeoChart('Popularity', $popularity, [
'colorAxis' => [ 'minValue' => 0, 'colors' => ['#FF0000', '#00FF00']], //ColorAxis Options
'datalessRegionColor' => '#81d4fa',
'displayMode' => 'auto',
'enableRegionInteractivity' => true,
'keepAspectRatio' => true,
'region' => 'world',
'magnifyingGlass' => ['enable' => true, 'zoomFactor' => 7.5], //MagnifyingGlass Options
'markerOpacity' => 1.0,
'resolution' => 'countries',
'sizeAxis' => null ,
'backgroundColor'=> '#81d4fa',
]);

yii2 file extension validation not works

I have rule in my model like this
public function rules()
{
return [
[['tbl_data_induk_mahasiswa_id'], 'required'],
[['tbl_data_induk_mahasiswa_id'], 'integer'],
[['nama'], 'file','extensions'=>'png,jpg','maxSize' => 1024000,'tooBig' => 'Size maksimum adalah 1 MB'],
[['nama'], 'string', 'max' => 300],
[['tbl_data_induk_mahasiswa_id'], 'unique'],
[['tbl_data_induk_mahasiswa_id'], 'exist', 'skipOnError' => true, 'targetClass' => TblDataIndukMahasiswa::className(), 'targetAttribute' => ['tbl_data_induk_mahasiswa_id' => 'id']],
];
}
i have form like this
<?php
use yii\helpers\Html;
//use yii\widgets\ActiveForm;
echo Html::beginForm(
['mahasiswa-foto-biodata/update'],
'post',
['enctype' => 'multipart/form-data'] //if you want to upload file with post
); ?>
<div class="form-group form-file-upload form-file-multiple">
<?= Html::activeFileInput(
$model,
'nama',
['class' => 'inputFileHidden', 'multiple' => '']
); ?>
<div class="input-group">
<?= Html::activeTextInput(
$model,
'nama',
[
'class' => 'form-control inputFileVisible',
'placeholder' => 'Single File',
]
); ?>
<span class="input-group-btn">
<button type="button" class="btn btn-fab btn-round btn-primary">
<i class="material-icons">attach_file</i>
</button>
</span>
</div>
</div>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?= Html::endForm(); ?>
I can not use activeForm widget because i must create html form that suit with my template, the form is work, the file succesfull uploaded, the problem is every tipe file is success uploaded, not just only png or jpg, but if i change the max rule for nama to [['nama'], 'string', 'max' => 2],then i upload a file that have name's length more than two the file can not be uploaded.
Any help?
Please check your form, you have 02 types of input with the same name ("nama"). One is "file", one is "text"
I think it is the reason that make your form does not works correctly!

Laravel 5.4 mail markdown 2 button inline

I would like to know how to place the button next to each other.
Now it is on a separate line.
#component('mail::message')
Dear {{$vendor_name}}
Product {{$product_id}} : {{$product_name}} price id : {{$price_id}} will expire on {{$date_expire}}.
Please renew price.
#component('mail::button', ['url' => 'http://phuketjettour.com/', 'color' => 'green'])
Phuket Jet Tour
#endcomponent
#component('mail::button', ['url' => 'http://phuketjettour.com/s/vendors'])
Vendor submission
#endcomponent
Thanks,<br>
Phuket Jet Tour
#endcomponent
Dynamic number of inline buttons
For me the following worked to create 2, 3, 4 (dynamic number) of buttons inline in Laravel markdown mails:
1) Add a new directory for your custom component
First lets extend the mail configuration to include our new directory for components:
config/mail.php
<?php
// ...
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
resource_path('views/emails/components') // <-- This line was added
],
],
2) Create the new component for inline buttons
You need to create both, the HTML and the text version of the component. Otherwise you will get a InvalidArgumentException "View $name not found":
www/resources/views/emails/components/html/buttons.blade.php
This is the HTML file:
<table class="action" align="center" width="100%" cellpadding="0" cellspacing="0" role="presentation">
<tr>
<td align="center">
<table width="100%" border="0" cellpadding="0" cellspacing="0" role="presentation">
<tr>
<td align="center">
<table border="0" cellpadding="0" cellspacing="0" role="presentation">
#if(null !== ($headline ?? null))
<tr><td><h2 style="text-align: center;">{{ $headline }}</h2></td></tr>
#endif
<tr>
<td>
#foreach($buttons as $button)
{!! $button['slot'] !!}
#endforeach
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
www/resources/views/emails/components/text/buttons.blade.php
This is the text file
#if(null !== ($headline ?? null))
{{ $headline }}
------------------------------
#endif
#foreach($buttons as $button)
{!! $button['slot'] !!}: {{ $button['url'] }}
#endforeach
3) Include the new component in your mails:
Now you can just include the component in your markdown emails like so:
Example with 2 inline buttons and a headline:
#component('mail::buttons', [
'headline' => 'Share link',
'buttons' => [
[
'url' => 'https://wa.me/?text=' . urlencode('Whatsapp text'),
'slot' => 'WhatsApp',
],[
'url' => 'https://t.me/share/url?text=' . urlencode('telegram text'),
'slot' => 'Telegram',
]
]
])
#endcomponent
Example with 3 inline buttons without a headline:
#component('mail::buttons', [
'buttons' => [
[
'url' => 'https://wa.me/?text=' . urlencode('Whatsapp text'),
'slot' => 'WhatsApp',
],[
'url' => 'https://t.me/share/url?text=' . urlencode('telegram text'),
'slot' => 'Telegram',
],[
'url' => 'https://twitter.com/intent/tweet?text=' . urlencode('Twitter text'),
'slot' => 'Twitter',
]
]
])
#endcomponent
Example with 3 inline buttons with different colours:
#component('mail::buttons', [
'buttons' => [
[
'url' => 'https://wa.me/?text=' . urlencode('Whatsapp text'),
'slot' => 'WhatsApp',
'color' => 'blue' // This is the default
],[
'url' => 'https://t.me/share/url?text=' . urlencode('telegram text'),
'slot' => 'Telegram',
'color' => 'green'
],[
'url' => 'https://twitter.com/intent/tweet?text=' . urlencode('Twitter text'),
'slot' => 'Twitter',
'color' => 'red'
]
]
])
#endcomponent
I have done it like this, ofcourse the css should be in a separated file
<style>
.email-row {
}
.email-col-2 {
width: 49%;
display: inline-block;
}
</style>
#component('mail::message')
<div class="email-row">
<div class="email-col-2">
#component('mail::button', ['url' => '453634', 'color' => 'light'])
btn1
#endcomponent
</div>
<div class="email-col-2">
#component('mail::button', ['url' => '123', 'color' => 'green'])
bnt2
#endcomponent
</div>
</div>
#endcomponent
When passing a variable to a blade template, use a single quote ( ' ) instead of a double quote ( " ).
$btn_style = " color: #FFF; border: 1px solid #FEFEFE; padding: 5px 30px;";
$buttons = '<span style="text-align: center; width: 100%; display: inline-block;">
Accept
Decline
</span>';
To render this code:
Edit your App\Mail
$this
->subject('Subject')
->markdown('emails.tempalte')
->with([
'buttons' => $buttons,
]);
Blade Template view\emails:
{!! $buttons !!}
Hope this helps.
you can put it in one <div>
For example:
<div class = "row>
your buttons here
</div>
If it doesn't help please share your code
Try this:
<span style="display: inline;">
#component('mail::button', ['url' => 'http://phuketjettour.com/', 'color' => 'green'])
Phuket Jet Tour
#endcomponent
#component('mail::button', ['url' => 'http://phuketjettour.com/s/vendors'])
Vendor submission
#endcomponent
</span>
It's just a work around. I've inspect the email from a laravel project.
try this in place of your component for button :
Phuket Jet Tour
SAMPLE !
it inlines your button. then just adjust other element. If you want to put the button on the markdown then you do like:
On your markdown:
$button1= " Phuket Jet Tour";
$button2 = "SAMPLE !";
$emailMarkdown = $this->markdown('your_email_template')
->subject('your_subject)
//you will define here the variables you need to pass in the template
->with([
'emailBody' => $emailBody,
'button_first' => $button1,
'button_second' => $button2,
]);
return $emailMarkdown;
then on the email template:
#component('mail::message')
Dear {{$vendor_name}}
Product {{$product_id}} : {{$product_name}} price id : {{$price_id}} will expire on {{$date_expire}}.
Please renew price.
{!!$button_first!!} {!!$button_second!!}
#endcomponent
To fix the issue, just place this code in email blade file:
<div style="text-align: center">
Cancel
Reschedule
Confirm
</div>

Lavacharts display 2 Piecharts, second chart has no data

I am trying to display 2 piechart in same view, this is my view code :
<div class="panel-body form-horizontal">
{{-- <div id="morris-donut-chart"></div> --}}
<div class="form-group">
<div id="chart-div"></div>
#piechart('tgt','chart-div')
</div>
<div class="form-group">
<div id="chart-div2"></div>
#piechart('capai','chart-div2')
</div>
</div>
both success display, but the second chart has no data.
Piechart
i think the variable of data table is not problem , when i use dd(), it's has data.
Data of Capai
my controller code :
public function statistik()
{
$lava = new Lavacharts;
$ket = array("totalTarget" => 0, "totalCapai" => 0);
$target_ = Target::select('grup')
->selectRaw("SUM(nilai) AS jumlah")
->groupBy('grup')
->get()
->toArray();
$data = \Lava::DataTable();
$data->addStringColumn('Target')
->addNumberColumn('Percent');
foreach($target_ as $row){
$data->addRow([$row['grup'], $row['jumlah'] ]);
$ket["totalTarget"] += $row['jumlah'];
}
\Lava::PieChart('tgt', $data, [
'title' => 'Target :',
'height' => '300',
'is3D' => true,
]);
$capai_ = Faktur::select('nama')
->selectRaw('SUM(qty) AS jumlah')
->groupBy('sub_group')
->get()
->toArray();
$data_capai = \Lava::DataTable();
$data_capai->addStringColumn('Pencapaian')
->addNumberColumn('Percent');
foreach($capai_ as $row_){
$data_capai->addRow([$row_['nama'], $row_['jumlah'] ]);
$ket["totalCapai"] += $row_['jumlah'];
}
// dd($data_capai);
\Lava::PieChart('capai', $data_capai, [
'title' => 'Pencapaian :',
'height' => '300',
'is3D' => true,
]);
return view('dashboard', compact('lava', 'ket'));
}
Is there something I miss?
I already fixed it.
All I need is to convert data to Float.

Resources