I'm using Laravel 5.8 and I want to make a popup system so that Admins can add custom images and custom text, and then at the blade, a popup must be appeared based on that information.
Here is the table structure of popups
:
1 id Primary bigint(20)
2 datep varchar(191)
3 title varchar(191)
4 linkp varchar(191)
5 text varchar(191)
6 image_path varchar(191)
7 created_at timestamp
8 updated_at timestamp
And this is the Javascript part of the popup:
<script>
$(document).ready(function(){
let popup_shown = false;
let cookies = document.cookie.split('; ');
for( let i=0; i<cookies.length; i ){
cookie = cookies[i].split('=');
if( cookie[0] == 'oly12_reg_ext2_popup_shown' )
popup_shown = true;
}
if( !popup_shown ){
Swal.fire({
html: '<a href="#"><img style="width: 100%;" src="{{ URL::to('/') }}/popup.jpg"></a>',
showConfirmButton: false
});
document.cookie = "oly12_reg_ext2_popup_shown=1; path=/";
}
});
</script>
But now the problem is I don't know how to mix Laravel and Javascript together in order to show the popup messages.
For example it should be looked like something like this as example:
@if(count($popups)>0)
$(document).ready(function(){
let popup_shown = false;
let cookies = document.cookie.split('; ');
for( let i=0; i<cookies.length; i ){
cookie = cookies[i].split('=');
if( cookie[0] == 'oly12_reg_ext2_popup_shown' )
popup_shown = true;
}
if( !popup_shown ){
@foreach($popups as $popup)
Swal.fire({
html: '<a href="{{ $popup->linkp }}"><img style="width: 100%;" src="{{ URL::to($popup->image_path) }}"></a>',
@endforeach
@endif
But this is obviously wrong.
So the question is, how can I show Laravel retrieved results from the DB in a Javascript code?
CodePudding user response:
Inside your controller, you can pass the popup data to a variable and pass it into the view like so,
Inside the controller;
$output = "";
$popups = PopUp::all();
if($popups->count() > 0)
{
foreach($popups as $popup)
{
$output .=' <a href=" '.$popup->linkp.' "><img src=" '. URL::to($popup->image_path).' " style="width: 100%;"></a>';
}
json_encode($output)
Then inside your blade view javascript,
@section('scripts')
<script>
$(document).ready(function(){
let popup_shown = false;
let cookies = document.cookie.split('; ');
for( let i=0; i<cookies.length; i ){
cookie = cookies[i].split('=');
if( cookie[0] == 'oly12_reg_ext2_popup_shown' )
popup_shown = true;
}
if( !popup_shown ){
var popup_data = '{{!! $output !!}}'
Swal.fire({ html:popup_data });
}
</script>
@endsection