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

zeros2077's avatar

How to simplify code with routes in laravel?

I'll try to explain as best I can. We know that route files can only be executed inside php files but I wanted to call them inside a javascript file using the ajax inside. Another thing, let's say I have a blade file that will have a variable that can only be used within the file that the route refers to. otherwise it will give "not found" but I wanted to run it inside an ajax file also inside a javascript-only file I'll explain once again we have the default blade file called main it will load in addition to all the configuration of the pages the functions by javascript but these javascript requests inside a php is ugly and bad. need to be inside a js file. in addition to the route not being found outside of a blade file, I don't know if you understood well

0 likes
15 replies
tykus's avatar

Can you format and punctuate your question(s) so it is easily readable? It is an unreadable mass of words right now.

1 like
zeros2077's avatar

@tykus allright You already worked with ajax requests with routes example: {{ route('blabla')}} so you know they don't work outside of a php file. this is the first problem because i wanted to separate js from php the second problem let's say the route you are using is an update so you will need an id to reference this correct id? {{ route('change_product',['id'=>$product->id])}} so the blade file that you will reference inside the web in case the "atualizar.blade" has to have these variables correct? but what if I'm referencing this file but it's running inside the "main.blade" main that will have all the configuration of the page. because the id needs to exist inside that is the question, could you understand it better?

tykus's avatar

That's not much better @zeros2077 - don't be afraid of paragraphs!!!

We know that route files can only be executed inside php files but I wanted to call them inside a javascript file using the ajax inside

You can expose you Laravel routes to javascript using Laravel Ziggy - which includes a javascript version of the route helper method.

let's say I have a blade file that will have a variable that can only be used within the file that the route refers to

What the Blade template needs (in terms of defined variables) in not really related to the Route; only what data is passed into the view from wherever it is called.

zeros2077's avatar

@tykus laravel ziggs can i pass the id along with the variable? Like: url:"{{ route('alterar_produto',['id'=>$produto->id])}}", to url :route('teste',['id'=>$produto->id);

tykus's avatar

@zeros2077 not 100% sure what you're asking, are we working the PHP or Javascript here?

1 like
zeros2077's avatar

@tykus both, from my default route file i need the ir of the type function like in the form:url: this will be the post :"{{ route('change_product',['id'=>$produto->id])}}", Using ziggs its like: route('test') So it will be: route(' change_product',['id'=>product->id]); did you understand now?

tykus's avatar

@zeros2077 the Javascript equivalent (obviously) will not be using PHP's object operator:

// say you have a `product` Object
route('change_product', product.id)
zeros2077's avatar

@tykus keep telling me "Uncaught ReferenceError: product is not defined"

tykus's avatar

@zeros2077

// say you have a product Object

What do you have (in Javascript) to represent/identify the Product?

tykus's avatar

@zeros2077 🤷‍♂️ genuinely I have no idea. Remember this is your application; I have no idea what you're working with except what you share.

1 like
zeros2077's avatar

@tykus I will send you my controller update

public function update(Request $request, $id){
    <br>$produto=Produto::findOrFail($id);
    $produto->update([

    'Nome'=>$request->nome,
    'custo'=>$request->custo,
    'preco'=>$request->preco,
    'quantidade'=>$request->quantidade,
    'Marca'=>$request->marcas,
      'Voltagem'=>$request->Voltagem,
      'Descricao'=>$request->Descricao,
    ]);

    $url = "http://localhost:8000/";

    $nome['success']=false;
    $nome['message']='Alterado com sucesso!!!';
    echo json_encode($nome);
    $json=json_encode($produto);
    return;
}
 

Now the javascript right


$('form[name="FormEdit"]').submit(function(event){
    event.preventDefault();
    var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' );

       $.ajax({
        type:'POST',


    url:route('alterar_produto', json_obj.id),
        data: $(this).serialize(),
        dataType:'json',
        success:function(response){

            if(response.success===true){
                window.location.href=route('alterar_produto',$produto.id);


            }else{

                $('.messageBox').removeClass('d-none').html(response.message).delay().fadeIn().delay(1000).fadeOut(300);



            }
            console.log(response);

        }




    });
       });

I think that's it, did you understand well? if you need more details just let me know

tykus's avatar

@zeros2077 you need to have the Product object available whenever you render the form - not alone after you update. Is there an edit action?

1 like
zeros2077's avatar

@tykus yes it have


public function edit($id){
    $product=Prod::findOrFail($id);
   return view('produts.edit',['product'=>$product]);


}
zeros2077's avatar

i tried to use the :

route('alterar_produto',{id : this.id})

and of course

   var json_obj = jQuery.parseJSON ( ' + <?php echo $json; ?> + ' ); 

But they give me the error

POST /products/edit 404 (Not Found)

Please or to participate in this conversation.