Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shahr's avatar
Level 10

How to bring code from Laravel to JavaScript?

How to bring code from Laravel to JavaScript?

@foreach($amazings as $product)
	<p id="timer">{{ $product->amazing->timestamp }}</p>
@endforeach 

script

<script>
    let startTime = {{ $product->amazing->timestamp }}; // database unix-timestamp value
    setInterval(() => {
        let curTime = (new Date()).getTime() / 1000;
        document.getElementById("timer").innerText = (`${startTime-curTime}`).toHHMMSS();
    }, 1000);
</script>
0 likes
21 replies
Sinnbeck's avatar

What does that mean? Also ids on elements should be unique, so setting multiple p elements to "timer" is a bad idea. Use a class if it should be on multiple

shahr's avatar
Level 10

@Sinnbeck I changed this like

<p class="timer">{{ $product->amazing->timestamp }}</p>

And

document.getElementsByClassName("timer").innerText = (`${startTime-curTime}`).toHHMMSS();

But it did not display and show

Sinnbeck's avatar

@qqqq Sorry but I dont understand the point of the code? Why not just do everything with php?

shahr's avatar
Level 10

@Sinnbeck

In the first post, This code always displays in the first row. While I chose a foreach ring.

In the second post. it did not show.

Sinnbeck's avatar

@qqqq As I have no clue what you want to do, I have no chance of giving you an answer.

Sinnbeck's avatar

@qqqq What is a timer? A countdown? Or the current time? Do you expect it to increse every second? These are just a few of the questions you should at least provide.

Sinnbeck's avatar

@qqqq Ok if that the amount of effort you want to put into explaining what you are trying to do, I will put the same amount of effort into giving an answer

Use a setInterval() to decrement it every second. Give javascript seconds, to make it easy to calculate and display.,

shahr's avatar
Level 10

@Sinnbeck I already made it, but I don't know why it doesn't show how to display it.

Sinnbeck's avatar

@qqqq Then show the code. That code you have shown does not seem correct. There is no setInterval and is it just for one product? If so, why do you have a foreach?

Sinnbeck's avatar

@qqqq And the answer to my question?

is it just for one product? If so, why do you have a foreach?

Sinnbeck's avatar

@MichalOravec I should have known :(

@oxbir yet your javascript just uses the last one.. Get the value from the dom. If you dont know how to do that.. research

Sinnbeck's avatar

@qqqq Really? The point is that you are asking someone to write the final code for you instead of taking the time to actually learn yourself. I mean instead of writing "how?", would it maybe be smarter to try googling "how to get data from the dom using javascript" or similar.

Or give that AI chat a shot. It will ACTUALLY write the code for you, free of charge

Please or to participate in this conversation.