Is it correct to mix JSON format with Mysql?

Asked

Viewed 81 times

-1

I am helping to develop a web application in Laravel for a company. It has several Modals included in them (including modal that leads to another modal).

To call these modals, I am using Jquery, as the example below:

$('.classe-do-modal').on('click', function(e) {
    e.preventDefault();
    let modal = $('#idDoModal');   

    modal.modal({show : true});    
});

In my controller, I am returning the values in JSON format within my function show.

public function show($id){
    $variavelModel = Model::where('outro_model_id',$id)->orderBy('created_at', 'desc')->get();
    return response()->json($variavelModel);
}

In another Javascript file, you also have the following commands:

      let p = JSON.parse($(this).attr('data-entity'));

      if(p.id) {
            $.ajax({
                url: 'url/daRota/'+p.id,
                type: "GET",
                data : {"_token":"{{ csrf_token() }}"},
                dataType: "json",
                success:function(data) {
                  if(data){ 
                    $('#id-da-div').empty();     
                    $.each(data, function(key, value){
                      $('#id-da-div').append(value);
                    });

                  }
                }
              });
            }

And to register the data, I have as the example below:

 public function store(Request $request){
        MeuModel::create(array_merge($request->all(, ['outro_model_id'=>$request->outro_model_id]));

        $variavel_model = MeuModel::where('outro_model_id',$request->outro_model_id)->get()->count();        

        OutroModel::where('id', $request->outro_model_id)->update('outro_model', $variavel_model);

        alert()->success('Sucesso', 'cadastrada com sucesso!');
        return back();

    }

Above there is only one example of how I am registering the data I want. I am using the database.

But the main question is this. Is it correct to use the database to register and then remove the data from the database and turn it to JSON? As an example using an AJAX request to get use of my route in Laravel? At first, I am not able to pull the data directly from the database without the AJAX request. I believe this is because of the modals. It is correct to use this way to get the data by mixing JSON with Mysql?

  • 1

    And what problem are you thinking you might have? Why do you think one thing has to do with another?

  • I’m not sure if this method would be a "gambiarra" or an efficient method to solve the problem.

  • 2

    It is correct to use the database to register and then remove the data from the database and turn it to JSON?, I don’t know if I understood your doubt well but the database saves the data in its own format that doesn’t matter to the code (even if the database can save in json), because it returns the data and you must transform them in what is necessary to present, be it json or text, csv, a table or something, so I don’t see any problems there. Now this and Ajax are completely different things in your question

  • Thanks @Ricardopunctual, clarified my question. Already in question to Ajax, I’m still confused with its functionality. I know it makes sense in matters like requisitions. But still in my head I am assimilating a lot to the JSON format because it is what I see most regarding an explanation of this functionality. In online tutorials for example I see some cursinhos using JSON as an example to explain AJAX.

2 answers

1


In the case presented above you are using a Mysql database, that is, this is where you are persisting your application data.

JSON, on the other hand, is a data structure that you are using to communicate the front-end with back-end, in this case it is not quite right or wrong, actually the error is in how you interpret "mixing JSON with Mysql".

You are not mixing JSON with Mysql, you are using a Mysql database to persist data and JSON to define a communication data structure between front-end and back-end.

Laravel has some collections, methods and helpers to simplify some tasks, such as taking a value that comes from the database and formatting it for the JSON data structure. Example: https://laravel.com/docs/5.8/responses#json-Responses

You’re going the right way...

  • Your answer is complete?

  • I added now. I’m sorry, by mistake I ended up publishing incompletely.

  • It seems to me that I was wrong about the title itself. I am very doubtful about the JSON. 'Cause it seems like a confusing way to turn the data into JSON yet. But your answer has already taken away my doubt.

  • Perfect, like you said, is the answer. Don’t take what I’ll say next as the only universally adopted solution and practice, but consider it: we usually use the JSON structure to build API or handle asynchronous communication, it’s an open format, more elegant than XML, easily manipulated and visually pleasing. It is very common to see ready-made solutions that transmit data in JSON, mainly between the back-end and front-end, this gives you flexibility, you can "plug" a front-end to your application, just that it handle JSON and the structure you created...

1

All right! Mysql supports JSON format! Remember to use it in the format of the column in the table! In the Laravel Migration it is possible to use the command

$table->json('modal_content');

This creates the JSON type column!

In the view, you can use the Blade Template to convert the JSON modal data directly into the variable that will fill the modal.. ie:

Instead of:

        $.ajax({
            url: 'url/daRota/'+p.id,
            type: "GET",
            data : {"_token":"{{ csrf_token() }}"},
            dataType: "json",
            success:function(data) {
              if(data){ 
                $('#id-da-div').empty();     
                $.each(data, function(key, value){
                  $('#id-da-div').append(value);
                });

              }
            }
          });
        }

Use:

$('#id-da-div').append({{ $modal_value }}); // sendo $modal_value uma variável PHP obtida pelo controller e enviada para a view !

Good luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.