DEV Community

Cover image for Elm with Laravel
Gayan Hewa
Gayan Hewa

Posted on

Elm with Laravel

I have been messing around with Elm the past week or so. Especially because of the potential to get a brainf*ck when getting started with Frontend development these days. Elm offers something really attractive. Simpler eco-system. Maybe I am drunk. But this is too attractive to not consider, especially for someone like me who is predominantly a backend developer.

After digging around, I wanted to do an experiment and try to see how I can get a small Elm component to render on one of my existing apps. This was surprisingly easy.

I started by:

  1. Creating an Elm file for the test component using the counter example
import Browser
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)

-- MAIN

main =
  Browser.sandbox { init = init, update = update, view = view }

-- MODEL

type alias Model = Int

init : Model
init =
  0

-- UPDATE

type Msg = Increment | Decrement

update : Msg -> Model -> Model
update msg model =
  case msg of
    Increment ->
      model + 1

    Decrement ->
      model - 1

-- VIEW

view : Model -> Html Msg
view model =
  div []
    [  div [] [text "My fancy counter"]
        , button [ onClick Decrement ] [ text "-" ]
    , div [] [ text (String.fromInt model) ]
    , button [ onClick Increment ] [ text "+" ]
    ]

Once I have this, I added another file to create the element and mount it.


import { Elm } from "./Counter.elm";

Elm.Main.init({
    node: document.querySelector("counter"),
});

Lastly, I added the newly created element <counter></counter> to my view.

@extends('layouts.app')

@section('content')
<counter></counter>
@endsection

Since I was using parcelJS, I didn't have to anything just had to make sure the js file was an entry point to the build command.

parcel build resources/assets/js/*.js --out-dir public/dist --public-url ./

So this is the final outcome, this is no way production-ready. But it helps me experiment with Elm for some parts of the application.

Alt Text

Top comments (0)