rjruiz

rjruiz

Member Since 1 Year Ago

Experience Points
2,620
Total
Experience

2,380 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
1
Lessons
Completed
Best Reply Awards
0
Best Reply
Awards
  • start your engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-in-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
2,620 XP
Jun
17
1 month ago
Activity icon

Replied to Saving Images With Laravel

Thanks for the information, I am almost sure that the steps I have taken to upload an image are correct but I doubt that this will work.

'''{!! Form::model($user, [ 'route' => $user->exists ? ['admin.users.update', $user->id] : 'admin.users.store', 'files' => true, 'enctype' => 'multipart/form-data', 'method' => $user->exists ? 'PUT' : 'POST' ]) !!}'''

Activity icon

Started a new Conversation Saving Images With Laravel

For some reason this does not allow me to upload an image from my form and I do not understand why this happens, where is my error?

<div class="row">
{!! Form::model($user, [
    'route' => $user->exists ? ['admin.users.update', $user->id] : 'admin.users.store',   
    'files' => true, 
    'enctype' => 'multipart/form-data',   
    'method' => $user->exists ? 'PUT' : 'POST'
]) !!}

 <div class="col-md-4">
        <div class="box box-primary">
            <div class="box-header with-border">
                <h3 class="box-title">Perfil</h3>                
            </div>
            <div class="box-body">                   
                <img width="300px" class="profile-user-img img-responsive img-circle" 
                    src="{{ Storage::url($user->user_photo)}}"                  
                    alt="{{ $user->name}}">
                    &nbsp;
                    &nbsp;
                <div class="form-group">              
                {!! Form::label('user_photo', 'Imagen de Perfil') !!}                    
                {!! Form::file('user_photo') !!}
                </div>
            </div>
        </div>       
    </div> 
{!! Form::close() !!}    
</div>

this is how I try to store the information entered from my controller

<?php

namespace App\Http\Controllers;

use App\User;
use App\Statu;
use DataTables;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Providers\UserWasCreated;
use Illuminate\Support\Facades\DB;
use App\Http\Requests\SaveUserRequest;
use Illuminate\Support\Facades\Storage;

class UserController extends Controller
{
   
    public function store(SaveUserRequest $request)
    {
        if ($request->ajax()){
            try {
                //  Transacciones
                DB::beginTransaction();

                // Creamos el usuario            
                $user = new User;   
                $user->name         = $request->get('name');
                $user->surname      = $request->get('surname');
                $user->nickname     = $request->get('nickname');
                $user->email        = $request->get('email');        
                $user->password     = $request->get('password');
                $user->gender       = $request->get('gender');  
                $user->address      = $request->get('address');
                $user->postcode     = $request->get('postcode');  
                $user->city         = $request->get('city');
                $user->province     = $request->get('province');  
                $user->phone        = $request->get('phone');
                $user->birthdate    = Carbon::parse($request->get('birthdate'));                      
                $user->status_id    = $request->get('status_id');            
               

                if ($request->hasFile('user_photo'))
                {
                    $user->user_photo = $request->file('user_photo')->store('public');
                }
                $user->save();
                
                // Enviamos el email
                // UserWasCreated::dispatch($user, $data['password']);
                //$user->update($request->validated()); 
    
                DB::commit();

            } catch (Exception $e) {
                // anula la transacion
                DB::rollBack();
            }
        }    
    }
}

Before saving I make a verification with dd ($ user);

 if ($request->hasFile('user_photo'))
                {
                    $user->user_photo = $request->file('user_photo')->store('public');
                }
                dd($user); 
                $user->save();

insepected I see that the field user_photo exists inside #fillable: array: 14 [ 13 => "user_photo" ]

but it is not within #attributes: array: 13

Result of all verification:

App\User {#1747
  #fillable: array:14 [
    0 => "status_id"
    1 => "surname"
    2 => "nickname"
    3 => "email"
    4 => "email_verified_at"
    5 => "password"
    6 => "gender"
    7 => "birthdate"
    8 => "province"
    9 => "city"
    10 => "address"
    11 => "postcode"
    12 => "phone"
    13 => "user_photo"
  ]
  #dates: array:1 [
    0 => "birthdate"
  ]
  #hidden: array:2 [
    0 => "password"
    1 => "remember_token"
  ]
  #casts: array:1 [
    "email_verified_at" => "datetime"
  ]
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #attributes: array:13 [
    "name" => "Rodrigo"
    "surname" => "Ruiz"
    "nickname" => "rjr"
    "email" => "[email protected]"
    "password" => "y$mZw/n4LpvK58bE3ghXx.NuabyduUhsA6FDmFBWVdjRBDaTVPJAaTO"
    "gender" => "Masculino"
    "address" => null
    "postcode" => null
    "city" => null
    "province" => "North Carolina"
    "phone" => "3434434"
    "birthdate" => "2020-06-17 00:00:00"
    "status_id" => "1"
  ]

What am i doing wrong?. Please help me with the solution

Apr
05
4 months ago
Activity icon

Started a new Conversation How To Update Chart.js According To The Option Selected From My Drop-down List?

I am trying to update my chart based on the option selected from my drop down list.

This is my JSON response:

{
"orders": [
{
"id": 4,
"name": "Luis",
"orders_by_user": 2,
"rol": 2
},
{
"id": 6,
"name": "Jose",
"orders_by_user": 1,
"rol": 2
},
{
"id": 7,
"name": "Miguel",
"orders_by_user": 1,
"rol": 2
}
]
}

Through ajax I obtain the data to make the graph and upload options to my drop-down list. A little snippet of code:

success: function (response) {             
            console.log(response);
            var order = [];
            var user = [];         

            for (var i in response.orders) {

                order.push(response.orders[i].orders_by_user);
                user.push(response.orders[i].name);              
                $("#operator").append('<option value='+response.orders[i].id+'>'+response.orders[i].name+'</option>');
                  
            }      
     
            renderChart(order, user);   

My Select:

<select class="form-control" name="operator" id="operator" >
    <option>All</option>                                                            
</select>   

With this I get the selected text from my drop-down list.

    var selectOption = $('#operator');                    
    selectOption.on('change', function() {   
        var option = $("option:selected", selectOption).text();

So if the selected option is "Luis", the graph would have to be updated graphing with the information that corresponds to "Luis" (see JSON response)

This is how I try to update my chart:

function renderChart(order, user) {
    var ctx = document.getElementById("orders").getContext('2d');
    var myChart = new Chart(ctx, {
      //code...
    }); 

    //my select
    var selectOption = $('#operator');                    
    selectOption.on('change', function() {  

         var option = $("option:selected", selectOption).text();
        myChart.data.labels = option;
        if (option == 'All') {
           myChart.data.labels = user,
           myChart.data.datasets[0].data = order;
        } else {
          myChart.data.labels = option;
          myChart.data.datasets[0].data = order;
        }
        myChart.update();
    });            

}

I think my problem is here:

} else {
    myChart.data.labels = option;
    myChart.data.datasets[0].data = order;
 }

The logic is if option is not equal to 'All', then myChart.data.labels = "Luis"; and myChart.data.datasets [0] .data = "2";

How can I go back through my user and order array? Exactly in user are all the names of the operators and in order are the quantities of completed orders that correspond.

Could you please guide me to solve this problem?

Apr
02
4 months ago
Activity icon

Replied to How To Return JSON Response From A Query With Eloquent?

@zsoltgyure I was thinking about the query you gave me as an answer, I modified your answer adapting it to mine, could you review it? Observe the json response that I receive, I am doubling the operator Luis with his number of orders

Apr
01
4 months ago
Activity icon

Replied to How To Return JSON Response From A Query With Eloquent?

@zsoltgyure I thank you for your contribution to answer my question. Modify your query to this:

        $users = collect();
        $orders = collect();

        $records = Order::with(['user' => function($query){
            return $query->withCount('orders');
        }])
        ->get();

        $records->each(function($record) use($users, $orders) {
            $users->push($record->user->name);
            $orders->push($record->user->orders_count);
        });

        return compact('users', 'orders');

As a result I get this:

{
"users": [
"Luis",
"Luis",
"Jose",
"Miguel"
],
"orders": [
2,
2,
1,
1
]
}

You may notice that the operator name Luis is repeated 2 times, as well as his completed work orders.

Why does this happen?. How could I avoid repeating the same name of the operator Luis and his number of completed orders? How can I solve it?

Activity icon

Replied to How To Return JSON Response From A Query With Eloquent?

@zsoltgyure dbtecind Great thanks for your time relating the users table and the orders table

Activity icon

Replied to How To Return JSON Response From A Query With Eloquent?

@zsoltgyure Thanks for your help, it is the result I was looking for, however I still think that this same query with fewer lines of code could be done using eloquent since I have all my related models.

Mar
31
4 months ago
Activity icon

Replied to How To Return JSON Response From A Query With Eloquent?

@zsoltgyure if it is a complex query, then you say that I only added what you have indicated and with that I solve my question? please confirm

Activity icon

Replied to How To Return JSON Response From A Query With Eloquent?

if that would be the end result but would you help me pass my query with eloquent

Activity icon

Started a new Conversation How To Return JSON Response From A Query With Eloquent?

I am working on this query: (I wish I could pass this same query using eloquent and return a JSON as response.)

public function getChart(Request $request)
    {      
        $_orders = DB::table('users')
            ->join('orders','orders.user_id','=','users.id')
            ->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')                        
            ->select('users.id','users.name', DB::raw('COUNT(orders.id) as orders_by_user'), 'model_has_roles.role_id as rol')                   
            ->where('model_has_roles.role_id', '2');
        $_orders->groupBy('orders.user_id', 'users.id',  'users.name',  'model_has_roles.role_id');
        $orders=$_orders->get();

        return ['orders' => $orders];

    }

This query is already resolved and returns me as a result: the name of the operator who was assigned a work order and the number of work orders in finished state that that operator has. for this, relate the users table and the orders table.

{
"orders": [
{
"id": 4,
"name": "Luis",
"orders_by_user": 2,
"rol": 2
},
{
"id": 6,
"name": "Jose",
"orders_by_user": 1,
"rol": 2
},
{
"id": 7,
"name": "Miguel",
"orders_by_user": 1,
"rol": 2
}
]
}

If you look at my query response, my array is called orders inside orders I get what I need:

"orders": [
{
"id": 4,
"name": "Luis",
"orders_by_user": 2,
"rol": 2
},

As I mentioned earlier, I wish I could pass this same query using eloquent and return a JSON in response.

How can I customize this JSON response? It would be something like this: separate name in one array and orders_by_user in another array

example of what I want to achieve

"users": [
{

"name": "Luis"
}
]
"orders": [
{

"orders_by_user": 2

}
]

I need your help

Mar
30
4 months ago
Activity icon

Replied to Chartjs With JSON Data In Laravel

@elanorriley this is the result of my original query:

{
"orders": [
{
"id": 4,
"name": "Luis",
"orders_by_user": 2,
"rol": 2
},
{
"id": 6,
"name": "Jose",
"orders_by_user": 1,
"rol": 2
},
{
"id": 7,
"name": "Miguel",
"orders_by_user": 1,
"rol": 2
}
]
}

With this data I am trying to make the graph but you tell me that this query does not return JSON in any way. I will work in the consultation seeing the link that you bought me

Activity icon

Replied to Chartjs With JSON Data In Laravel

@bobbybouwmann, @elanorriley thanks for your suggestions.

@elanorriley Since you tell me that you are using chart.js in a project you could check my update 1, Please you could see my report.js file that is the file that I use to show the graph maybe you could indicate the error that you have commented to me

Activity icon

Started a new Conversation Chartjs With JSON Data In Laravel

I am making a query to my database and with the results obtained make a graph using the library chart.js.

This is my query that I make through my getChart method in my ReportController controller:

public function getChart(Request $request)
    {
        $_orders = DB::table('users')
            ->join('orders','orders.user_id','=','users.id')
            ->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')                        
            ->select('users.id','users.name', DB::raw('COUNT(orders.id) as orders_by_user'), 'model_has_roles.role_id as rol')                   
            ->where('model_has_roles.role_id', '2');
        $_orders->groupBy('orders.user_id', 'users.id',  'users.name',  'model_has_roles.role_id');
        $orders=$_orders->get();

        return ['orders' => $orders]; 
     
    }

With this query I obtain the information of the name of the operator who was assigned a work order and I also obtain the number of work orders that he has in a finished state. I'm basically relating the orders table to the users table.

As a result of the query I return a JSON like the following:

{
"orders": [
{
"id": 4,
"name": "Luis",
"orders_by_user": 2,
"rol": 2
},
{
"id": 6,
"name": "Jose",
"orders_by_user": 1,
"rol": 2
},
{
"id": 7,
"name": "Miguel",
"orders_by_user": 1,
"rol": 2
}
]
}

It seems that the STRUCTURE OF MY JSON is not correct so that the library chart.js understands the data that I am passing it. Instead you would be needing a result like the following:


users: Array(3) 
{
     0: "Luis"
     1: "Jose"
     2: "Miguel"
}

orders_by_user: Array(3)
{ 
    0: 2
    1: 1
    2: 1 
}

So how to improve my original query? How to get the correct JSON structure for my chart?

UPDATED 1

So assuming that my original query is correct I use this my report.js file to make the graph.

report.js:

function renderChart(data, labels) {
    var ctx = document.getElementById("orders").getContext('2d');
    var myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [{
                label: 'ordenes',
                data: data,
                borderColor: 'rgba(75, 192, 192, 1)',
                backgroundColor: 'rgba(75, 192, 192, 0.2)',
                borderWidth: 1,
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true                        
                    }
                }]
            },
            title: {
                display: true,
                text: "Ordenes en estado terminado"
            },
        }
    });
}



function getChartData() {   

    $.ajax({
        url: '/admin/reports/getChart',
        type: 'GET',
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          },
        dataType: 'json',
        success: function (data) {

           // console.log(data);
            var data = [];
            var labels = [];



            for (var i in data) {
                data.push(data[i].orders_by_user);
                labels.push(data[i].name);

            }

            renderChart(data, labels);
        },
        error: function (data) {

            console.log(data);
        }
    });
}

$("#renderBtn").click(
    function () {
        getChartData();
    }
);

When you want to graph, simply no data is displayed, it is an empty graph.

grafico

Mar
26
4 months ago
Activity icon

Replied to Dynamic Graph With Chart.js And Vue.js

My problem is not knowing how to graph again once the operator is selected from the input select. Any suggestion?

Activity icon

Started a new Conversation Dynamic Graph With Chart.js And Vue.js

I have the following bar graph:

Grafico

As you can see I am showing all work orders in finished state that were assigned to users with the operator role. To this graph I have added a select that allows me to filter by operator name and then graph, that is, if I choose the operator Luis and press the search button, I should only graph Luis operator with all his completed orders, which in this case, you only have 2 orders in finished state.

I have the query, I have the graph working, I have the select.

My problem is not knowing how to graph again once the operator is selected from the input select, showing only the orders that the selected operator has. I suppose that the solution to this will be done within the script from where I am giving my variables, making the query to the url, etc.

How can I solve this problem?.

For the graph I am using the library chart.js and vue.js. So far everything stated above:

DashboardController:

With this GetOperator () method I get the users with the operator role in the input select.

public function GetOperator()
    {
        $operator = User::NotRole(['Admin', 'Supervisor'])->get();

        $data = [];
        $data[0] = [
            'id'   => 0,
            'text' =>'Seleccione',
        ];
        foreach ($operator as $key => $value) {
            $data[$key+1] =[
                'id'   => $value->id,
                'text' => $value->name,
            ];
            # code...
        }
        return response()->json($data);
    }

With this getOrders method ($ user = null, $ status = null, $ month = null), I query the database.

public function getOrders($user=null, $status=null, $month=null)
    {      

        $_orders = DB::table('users')
                        ->join('orders','orders.user_id','=','users.id')
                        ->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')                        
                        ->select('users.id','users.name', DB::raw('COUNT(orders.id) as orders_by_user'), 'model_has_roles.role_id as rol')                   
                        ->where('model_has_roles.role_id', '2');
        if($status!=0){
            $_orders->where('orders.status', $status);
        }
        if($user!=0){ // suponiendo que viene id de usuario
            $_orders->where('users.id', $user);
        }

        if($month!=0){ // suponiendo que viene id de usuario
            // $query->where('title', "LIKE", "%$title%");
            $_orders->where('orders.date', 'LIKE', "%-{$month}-%");
        }
                        $_orders->groupBy('orders.user_id', 'users.id',  'users.name',  'model_has_roles.role_id');
                        $orders=$_orders->get();

        return ['orders' => $orders, 'users'=> User::NotRole(['Admin', 'Supervisor'])->get()];


    }

}

Dashboard.vue:

Here I show the graph and the select

<div class="row">
    <div class="col-md-6">
        <div class="box box-primary">
            <div class="box-header with-border">
                <h3 class="box-title">Ordenes por operario</h3>
                <div class="box-tools pull-right">
                    <button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i>
                    </button>
                    <button type="button" class="btn btn-box-tool" data-widget="remove"><i class="fa fa-times"></i></button>
                </div>
            </div>
            <div class="box-body"> 
                <div class="card card-chart">
                    <div class="card-header">
                        <h4>Seleccione Operario</h4>                                          
                        <form class="form-inline">
                            <div class="form-group mx-sm-3">
                                <label for="exampleFormControlSelect1" class="sr-only">Operario</label>                                                        
                                <select class="form-control" id="select_users">
                                    <option></option>                                                            
                                </select>  

                            </div>                                                   
                            <button type="submit" class="btn btn-primary">Buscar</button>
                        </form>
                    </div>
                    <div class="card-content">
                        <div class="ct-chart">
                            <canvas id="order">
                            </canvas>
                        </div>                               
                    </div>
                    <div class="card-footer">
                        <p>Ordenes.</p>
                    </div>
                </div>                                          
            </div>
        </div>
    </div>
</div>        

Script:

Well inside the script in data, I define my variables, in the getOperarios method I make the query to the url '/ admin / dashboard / getOrders /' + user + '/' + status + '/' + month; I fill the select with the names of users with the role of operator and in turn I invoke the loadOperarios () method that will graph based on the past data.

<script>    

    export default {          
        data (){
            return {                    

                varOrders:null,
                charOrders:null,
                orders:[],
                varTotalOrders:[],               
                varMesOrders:[],

            }              
        },
        methods : {

            getOperarios(user=0,status=0,month=0){
                let me=this;
                var url= '/admin/dashboard/getOrders/'+user+'/'+status+'/'+month;
                axios.get(url).then(function (response) {
                    //  console.log(response);
                    var respuesta = response.data;
                    me.orders = respuesta.orders;
                    me.users = respuesta.users;
                    var select_users = document.getElementById("select_users");
                    $.each(me.users, function(key, value) {

                        var option = document.createElement("option");
                        option.text = value.name;
                        option.value = value.id;
                        select_users.add(option);
                    });
                    // //cargamos los datos del chart
                    me.loadOperarios();
                })
                .catch(function (error) {
                    console.log(error);
                });
            }, 

            loadOperarios(){
                let me=this;
                me.orders.map(function(x){                    
                    me.varMesOrders.push(x.name);
                    me.varTotalOrders.push(x.orders_by_user);
                    // me.varUser_id.push(x.user_id);

                });
                me.varOrders=document.getElementById('order').getContext('2d');

                me.charOrders = new Chart(me.varOrders, {
                    type: 'bar',
                    data: {
                        labels: me.varMesOrders, 
                        datasets: [{
                            label: 'Ordenes',
                            data: me.varTotalOrders,
                            backgroundColor: 'rgba(25, 111, 61, 0.5)',
                            borderColor: 'rgba(25, 111, 61, 0.5)',                         
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero:true
                                }
                            }]
                        }
                    }
                });
            } 

        }, 

        mounted() {

            this.getOperarios(); 

        }

    }

</script>

I honestly don't have much knowledge in vue.js so I need to move forward, I need someone to guide me with the solution, I think you can also get the same result by implementing char.js alongside jajax and jquery if necessary I am willing to change my mind.

Mar
15
4 months ago
Activity icon

Replied to How To Multiply An Integer By Hours, Minutes And Seconds With Jquery?

@rodrigo.pedra I am carrying out a test applying your suggestion, it turns out that when entering values ​​in the fields, the alert continues ("enter numbers in the fields"), when in fact there are already entered numbers, Entoces removed the validation and performed the test again, in this case it does not give me any results

Mar
14
4 months ago
Activity icon

Replied to How To Multiply An Integer By Hours, Minutes And Seconds With Jquery?

@rodrigo.pedra thanks for commenting then I test your answer and comment on the result

Activity icon

Replied to How To Multiply An Integer By Hours, Minutes And Seconds With Jquery?

@jlrdw Thanks for sharing the link, I am not giving an example that I need or I am not looking for the right way. In this case, would I have to pass the time to an integer to multiply integer with integer?

Activity icon

Replied to How To Multiply An Integer By Hours, Minutes And Seconds With Jquery?

@snapey the number of pieces would be an integer greater than zero and for the time it takes me to make a piece you have to enter it in time format (hh: mm: ss) with that multiply it. To the result show it in hh: mm: ss example 2 x 00:02:00

Activity icon

Started a new Conversation How To Multiply An Integer By Hours, Minutes And Seconds With Jquery?

I need to perform a mathematical operation which consists of calculating the total machining time.

This total time is obtained from the result of multiplying the number of parts to be manufactured (integer) by the time it takes me to manufacture a part (time in the format of hh: mm: ss), and this result must be obtained, converted to hour, minute and second format.

This is my html:

<div class="box box-info">
            <div class="box-header with-border">
                <h3 class="box-title">Tiempo de mecanizado</h3>                
            </div>            
            <div class="box-body">                 
                <div class="form-group">          
                    {!! Form::label('amount', 'Cantidad Mecanizada:') !!} 
                    {!! Form::text('amount', null, ['class' => 'form-control', 'id' => 'amount', 'placeholder' => 'Ingrese la cantidad de piezas
                     fabricadas']) !!}                       
                </div>
                <div class="form-group">          
                    {!! Form::label('time', 'Tiempo de mecanizado:') !!} 
                    {!! Form::text('time', null, ['class' => 'form-control', 'id' => 'time', 'placeholder' => 'Ingrese el tiempo de mecanizado']) !!}                       
                </div>
                <p class="resultado">Resultado: <span id="resultado">0</span></p>
                <button id="calcular">Calcular tiempo de mecanizado</button>
             </div>  
        </div>

This is my script:

I am working with the following script: with this script obviously integers are being multiplied, the point is as follows: my second variable (var secondValue = $ ('# time'). Val ()), has to accept the format that I am passing through my input $ ('# time') multiply and get the result in the format hours, minutes and seconds, clarified this How can I do this calculation? How can I get this result in the time format?

<script>

     $('#time').timepicker({
           showInputs: false,                   
           minuteStep: 1,       
           secondStep: 1,         
           showSeconds: true,
           showMeridian: false,
           defaultTime: false                    
     });


    $(function() {
        //Operación matemática
      $('#calcular').click(function(e) {
        e.preventDefault();

        //Almaceno los valores de los inputs
        var primerValor = $('#amount').val();
        var segundoValor = $('#time').val()

        //Condiciona para que acepte solo números usando las expresiones regulares
        if(primerValor.match(/^[0-9]+$/) && segundoValor.match(/^[0-9]+$/)){

            var resultado = parseFloat(primerValor) * parseFloat(segundoValor);

        }else{
            alert("Ingrese números en los campos");
        }
        //Muestro el resultado
        $('#resultado').text(resultado);
      });
    });
</script>
Mar
07
5 months ago
Activity icon

Replied to How To Update A HasOne Relationship?

@tisuchi great thank you very much for your clarification! That is what I needed to do!

Activity icon

Started a new Conversation How To Update A HasOne Relationship?

I need to update a hasOne relationship in my update method I am trying the following and it is not working.

update method

                $piece = Piece::with('program')->findOrFail($id); 
            
                $program = $piece->program()->update($request->all());

                $piece = $program->piece()->update([
                    'denomination' => $request['denomination'],
                    'code'         => $request['code'],
                    'time'         => $request['time'],
                    'part_piece'   => $request['part_piece'],         
                    'gag_id'       => $request['number_gag'],         
                    'program_id'   => $program->id                     
                ]);                           
             
                $piece->syncTools($request->get('tools'));

I really need to update what I have in my store method

store method:

 $program = Program::create($request->all());
            
                $piece = $program->piece()->create([
                    'denomination' => $request['denomination'],
                    'code'         => $request['code'],
                    'time'         => $request['time'],
                    'part_piece'   => $request['part_piece'],         
                    'gag_id'       => $request['number_gag'],         
                    'program_id'   => $program->id                     
                ]);                           
             
                $piece->syncTools($request->get('tools'));


So how can I update what has already been saved before?

this is my piece model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Piece extends Model
{
    protected $fillable = [
        'program_id','gag_id', 'denomination', 'code', 'part_piece', 'time', 'observation'
    ];
    
    

    public function program()
    {
         return $this->belongsTo(Program::class);
    } 
    
    public function gag()
    {
        return $this->belongsTo(Gag::class);
    } 
       
    public function tools() 
    {        
        return $this->belongsToMany(Tool::class)->withTimestamps();
    }   
   
    public function syncTools($tools)
    {
       $toolsIds = collect($tools)->map(function($tool){
            return Tool::find($tool) ? $tool :Tool::create(['tool' => $tool])->id;
        });                

        return $this->tools()->sync($toolsIds);
    }    
}

this is my program model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Program extends Model
{
    protected $fillable = [
        'name_program','number_program','part_program'
    ]; 
   
    public function piece()
    {
        return $this->hasOne(Piece::class);
    }

  
}

Mar
01
5 months ago
Activity icon

Started a new Conversation Show Error Message In Dynamic Fields

Within my form I have a dynamic table that allows me to enter tools. I encounter problems when displaying the required field error message for those dynamic fields. To validate the fields I am using a FromRequest file:


$rules = [             
        'denomination' => 'required',
        'code' => 'required',           
        'part_piece' => 'required',
        'number_gag' => 'required',          
        'number_program' => 'required',         
        'time' => 'required',         
    ];

    if($this->request->get('addmore')){
        foreach($this->request->get('addmore') as $key => $val)
        {
            $rules['addmore.'.$key.'.position'] = 'required';
            $rules['addmore.'.$key.'.code_tool'] = 'required';
            $rules['addmore.'.$key.'.code_insert'] = 'required';
            $rules['addmore.'.$key.'.quality'] = 'required';
        }
    }

    return $rules;

I can't see the error message in the dynamic fields of my table

HTML table:

                   <tbody>
                        @forelse ($piece->tools as $p)  
                        <tr>                      
                            <input name="addmore[{{$loop->index}}][insert_id]" value="{{ $p->insert->id }}" hidden/>                       
                            <input name="addmore[{{$loop->index}}][tool_id]" value="{{ $p->id }}" hidden/> 
                            <td>
                                <div class="form-group">                           
                                <td><input type="text" name="addmore[{{$loop->index}}][position]" value="{{ $p->position }}" placeholder="Posicion"class="form-control"/></td>
                                </div>
                            </td>
$("#dynamicTable").append( 
        '<tr>' +           
            '<td>' +
                '<div class="form-group">' +           
                    '<input type="text" name="addmore['+i+'][position]" placeholder="Posicion" class="form-control"/>' +
                '</div>' + 
            '</td>' +
            '<td><input type="text" name="addmore['+i+'][code_tool]" placeholder="Herramienta" class="form-control" /></td>' + 

Dynamica table script:

Js file:

$.ajax({
        url : url,
        method: method,
        data : form.serialize(),
        success: function (response) { 
            form.trigger('reset');
            $('#modal').modal('hide');
            $('#datatable').DataTable().ajax.reload();       
            
            swal({
                type : 'success',
                title : '¡Éxito!',
                text : '¡Se han guardado los datos!'
            });
        },
        error : function (xhr) {
            var res = xhr.responseJSON;
            if ($.isEmptyObject(res) == false) {
                $.each(res.errors, function (key, value) {
                    $('#' + key)
                        .closest('.form-group')
                        .addClass('has-error')
                        .append('<span class="help-block"><strong>' + value + '</strong></span>');
                        
                });
            }
        }
    })

I need the error message to be displayed as if it does with the other fields. Not if it has something to do for the other fields I use laravelcollective

this is one of my fields with laravelcollective where if it shows me the corresponding error message


                    <div class="form-group col-md-4">                                        
                        {!! Form::label('denomination', 'Denominación') !!}                       
                        {!! Form::select('denomination', $denomination, null, ['class' => 'form-control', 'id' => 'denomination', 'placeholder' => '']) !!}                              
                    </div> 
Activity icon

Replied to Validate Dynamic Fields With FromRequest In Laravel

@a4ashraf thank you now it is working correctly, now I present another problem I will continue with another question I suggest you see it thank you

Activity icon

Started a new Conversation Validate Dynamic Fields With FromRequest In Laravel

I am using a fromrequest file to validate each field of my form, I can observe the errors of those fields that are not dynamic, For those fields that if they are directly dynamic does not show the error, it is rare because if I am validating it as a required field in my fromrequest file.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class SavePieceRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $rules = [             

            'denomination' => 'required',
            'code' => 'required',           
            'part_piece' => 'required',
            'number_gag' => 'required',          
            'number_program' => 'required',         
            'time' => 'required',         

        ];

        if($this->request->get('addmore')){
            foreach($this->request->get('addmore') as $key => $val)
            {
                $rules['position.'.$key] = 'required';
                $rules['code_tool.'.$key] = 'required';
                $rules['code_insert.'.$key] = 'required';
                $rules['quality.'.$key] = 'required';
            }
        }

        return $rules;

    }
}

This is how I show the errors that my form fields have, but the fields that are dynamic that I add through jquery and that have errors I cannot visualize.

script:


$('#modal-btn-save').click(function (event) {
    event.preventDefault();

    var form = $('#modal-body form'),
        url = form.attr('action'),
        method = $('input[name=_method]').val() == undefined ? 'POST' : 'PUT';        

    form.find('.help-block').remove();
    form.find('.form-group').removeClass('has-error');

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
    });

    $.ajax({
        url : url,
        method: method,
        data : form.serialize(),
        success: function (response) { 
            form.trigger('reset');
            $('#modal').modal('hide');
            $('#datatable').DataTable().ajax.reload();       

            swal({
                type : 'success',
                title : '¡Éxito!',
                text : '¡Se han guardado los datos!'
            });
        },
        error : function (xhr) {
            var res = xhr.responseJSON;
            if ($.isEmptyObject(res) == false) {
                $.each(res.errors, function (key, value) {
                    $('#' + key)
                        .closest('.form-group')
                        .addClass('has-error')
                        .append('<span class="help-block"><strong>' + value + '</strong></span>');

                });
            }
        }
    })


});

I've realized that I need one (div class = "form-group") for each dynamic field to show the error message, because that's what my script requires, that's how my script shows the error of the fields that make up my form :

error : function (xhr) {
            var res = xhr.responseJSON;
            if ($.isEmptyObject(res) == false) {
                $.each(res.errors, function (key, value) {
                    $('#' + key)
                        .closest('.form-group')
                        .addClass('has-error')
                        .append('<span class="help-block"><strong>' + value + '</strong></span>');

                });
            }

but even so I cannot visualize the error message on my form for fields that are dynamic, I am trying the following within my dynamic table:

Part of my formb (tools section)

    <tbody>
                        @forelse ($piece->tools as $p)  
                        <tr> 

                            <input name="addmore[{{$loop->index}}][insert_id]" value="{{ $p->insert->id }}" hidden/>                       
                            <input name="addmore[{{$loop->index}}][tool_id]" value="{{ $p->id }}" hidden/> 
                            <td>
                                <div class="form-group">
                                    <input type="text" name="addmore[{{$loop->index}}][position]" value="{{ $p->position }}" placeholder="Posición" class="form-control"/>
                                </div>
                            </td>

In the same way I have a (div class = "form-group") in my script that allows me to add the dynamic field in this case to the position field

$("#dynamicTable").append( 
        '<tr>' +           
            '<td>' +
                '<div class="form-group">' + 
                    '<input type="text" name="addmore['+i+'][position]" placeholder="Posicion" class="form-control"/>' +
                '</div>' + 
            '</td>' +
            '<td><input type="text" name="addmore['+i+'][code_tool]" placeholder="Herramienta" class="form-control" /></td>' + 
Feb
18
5 months ago
Activity icon

Replied to Update Dynamic Table

@a4ashraf Great, pass me your email, I contact you

Activity icon

Replied to Update Dynamic Table

Observe @a4ashraf I made some modifications to my update () method so it is now:

 
                $piece  = Piece::with(['tools.insert'], 'gag', 'piece')->findOrFail($id); 
               
                $addmore = $request->addmore;
                $arrTool = [];

                foreach($addmore as $add)
                {
                    $insert = Insert::create([
                        'code_insert' => $add['code_insert'],
                        'quality'     => $add['quality']
                    ]);  

                    $tools = $insert->tools()->updateOrCreate([
                        'position'   => $add['position'],
                        'code_tool'  => $add['code_tool'],                   
                        'insert_id'  => $insert->id                            
                    ]);                     
                        
                    $arrTool[] = $tools->id;                  
                }    
                           
                $piece->gag()->update($request->all()); 
                $piece->program()->update($request->all()); 
               
                firts dd($piece);

                $piece = $program->piece()->update([
                    'denomination' => $request['denomination'],
                    'code'         => $request['code'],
                    'time'         => $request['time'],
                    'part_piece'   => $request['part_piece'],
                    'gag_id'       => $gag->id
                    
                ]);              
                       
                 second dd($piece);      
                $piece->tools()->syncWithoutDetaching($arrTool);

With these changes I receive an error just here: (update the associated tools)

    $piece->tools()->syncWithoutDetaching($arrTool);

error

message: "Call to a member function tools() on integer"

By way of clarification, when I make the first dd ($ piece), $ request has information, when I try with the second dd ($ piece) the request is completely empty, I think you should first solve this error: ("Call to a member function tools () on integer") update the tools that already exist.

Anyway, if you need the first request to pass, let me know

Feb
17
5 months ago
Activity icon

Replied to Update Dynamic Table

@a4ashraf Make the changes you indicated to me and throw this error:

    "message": "Array to string conversion",

at me just as it passes through this line:

    $gag = Gag::where('gag_id', $piece->id)->update($request->all());
                $program = Program::where('program_id', $piece->program_id)->update($request->all());
Activity icon

Replied to Update Dynamic Table

@a4ashraf

Making a dd () at the beginning of the method I get the following:

 public function update(Request $request, $id)
    {
        if ($request->ajax()){
            try {
                //  Transacciones
                DB::beginTransaction();
                
                $piece  = Piece::with(['tools.insert'])->findOrFail($id); 
                           
                dd($piece);
#attributes: array:10 [
    "id" => 6
    "program_id" => 6
    "gag_id" => 6
    "denomination" => "eje"
    "code" => "0340-0456-0/6"
    "part_piece" => 2
    "time" => "12:53:29"
    "observation" => null
    "created_at" => "2020-02-02 09:23:00"
    "updated_at" => "2020-02-02 09:23:00"
  ]

Making the change I receive this message:

    "message": "Array to string conversion",

I think it is due to this:

 $gag = Gag::where('gag_id', $id)->update($request->all());
 $program = Program::where('program_id', $id)->update($request->all());     

I think we are close to solving the error.

Activity icon

Replied to Update Dynamic Table

@snapey If I am trying this:

 $insert = Insert::update([
                    'code_insert' => $add['code_insert'],
                    'quality'     => $add['quality']
                ]);  

I receive the following error

"message": "Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically",

I just don't know how to solve it

Activity icon

Replied to Update Dynamic Table

@a4ashraf This is what my method currently looks like is obviously not working, please see the clarifications please, I am trying to update the information that has already been saved

 public function update(Request $request, $id)
    {
        if ($request->ajax()){
            try {
                //  Transacciones
                DB::beginTransaction();
                
                $piece  = Piece::with(['tools.insert'])->findOrFail($id); 
               
                $addmore = $request->addmore;
                $arrTool = [];

                foreach($addmore as $add)
                {
                     //i'm not sure about this (Insert::create)
                    $insert = Insert::create([
                        'code_insert' => $add['code_insert'],
                        'quality'     => $add['quality']
                    ]);  

                    $tools = $insert->tools()->updateOrCreate([
                        'position'   => $add['position'],
                        'code_tool'  => $add['code_tool'],                   
                        'insert_id'  => $insert->id                            
                    ]);                     
                        
                    $arrTool[] = $tools->id;                  
                }    
                       
                 //I have to update this:(Gag::create, Program::create)
                $gag     = Gag::create($request->all());
                $program = Program::create($request->all()); 
              
                $piece = $program->piece()->update([
                    'denomination' => $request['denomination'],
                    'code'         => $request['code'],
                    'time'         => $request['time'],
                    'part_piece'   => $request['part_piece'],
                    'gag_id'       => $gag->id,
                    'program_id'   => $program->id
                ]);              
          
                //update associated tools
                $piece->tools()->syncWithoutDetaching($arrTool);
            
                DB::commit();

            } catch (Exception $e) {
                // anula la transacion
                DB::rollBack();
            }
        }      
    }

My Model Piece: (fillable)

protected $fillable = [
        'program_id', 'gag_id', 'denomination', 'code', 'part_piece', 'time', 'observation'
    ];  
Activity icon

Replied to Update Dynamic Table

Hi, @a4ashraf thanks for answering. I'm using your second answer. My update method looks like this.

 $piece  = Piece::with(['tools.insert'])->findOrFail($id); 
               
                // $this->authorize('create', new Piece);                               
                // dd($request->all());

                $addmore = $request->addmore;
                $arrTool = [];

                foreach($addmore as $add)
                {
                    $insert = Insert::create([
                        'code_insert' => $add['code_insert'],
                        'quality'     => $add['quality']
                    ]);  

                    $tools = $insert->tools()->updateOrCreate([
                        'position'   => $add['position'],
                        'code_tool'  => $add['code_tool'],                   
                        'insert_id'  => $insert->id                            
                    ]);                     
                        
                    $arrTool[] = $tools->id;                  
                }    
             
                $gag     = Gag::update($request->all());
                $program = Program::update($request->all()); 

I get an error right here, I know this is wrong:


                $gag     = Gag::update($request->all());
                $program = Program::update($request->all()); 

error:

message: "Non-static method Illuminate\Database\Eloquent\Model::update()
Feb
16
5 months ago
Activity icon

Replied to Update Dynamic Table

Hello @a4ashraf I am trying to update the information related to a piece through the update method, I know you could help me, since you guided on how to save the information with the store method

Activity icon

Started a new Conversation Update Dynamic Table

Greetings I have problems to update the information that has associated to piece, precisely with its tools, Within my form I have a dynamic table that allows me to add or remove fields dynamically When you want to update the tools associated with the piece I receive the following error:

message: "Trying to get property 'id' of non-object"
exception: "ErrorException"

this is my update method (I think the problem is right here)

        $piece  = Piece::with(['tools.insert'])->findOrFail($id); 

                $addmore = $request->addmore;
                $arrTool = [];

                foreach($addmore as $add)
                {
                    $insert = Insert::create([
                        'code_insert' => $add['code_insert'],
                        'quality'     => $add['quality']
                    ]);  

                    $tools = $insert->tools()->update([
                        'position'   => $add['position'],
                        'code_tool'  => $add['code_tool'],                   
                        'insert_id'  => $insert->id                            
                    ]);                     
                        
                    $arrTool[] = $tools->id;                  
                }              

How could I solve this problem that I am doing wrong?

Feb
15
5 months ago
Activity icon

Replied to How Get Value From Dynamic Fields?

Hi, @a4ashraf I found a solution to my problem, when I was referring to the fact that I was not visualizing the tools associated with your piece, it is because the foreach was wrongly declared just here:


                        <tr>  
 @foreach ($piece->tools as $p)  
                            <td><input type="text" name="addmore[0][position]" value="{{ $p->position }} " placeholder="Posición"  class="form-control select2" /></td>                                                 
                            <td><input type="text" name="addmore[0][code_tool]" value="{{ $p->code_tool }}"  placeholder="Herramienta"class="form-control" /></td>                        
                            <td><input type="text" name="addmore[0][code_insert]" value="{{ $p->insert->code_insert }}" placeholder="Inserto" class="form-control" /></td>                       
                            <td><input type="text" name="addmore[0][quality]" value="{{ $p->insert->quality }}" placeholder="Calidad" class="form-control" /></td>                      
                        
                            <td><button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus-square"></i></button></td>
                           @endforeach 
                        </tr>  
               

My solution was to declare it above before :

 @foreach ($piece->tools as $p)  
                        <tr>  
                            <td><input type="text" name="addmore[0][position]" value="{{ $p->position }} " placeholder="Posición"  class="form-control select2" /></td>                                                 
                            <td><input type="text" name="addmore[0][code_tool]" value="{{ $p->code_tool }}"  placeholder="Herramienta"class="form-control" /></td>                        
                            <td><input type="text" name="addmore[0][code_insert]" value="{{ $p->insert->code_insert }}" placeholder="Inserto" class="form-control" /></td>                       
                            <td><input type="text" name="addmore[0][quality]" value="{{ $p->insert->quality }}" placeholder="Calidad" class="form-control" /></td>                      
                        
                            <td><button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus-square"></i></button></td>
                      
                        </tr>  
                    @endforeach 

thanks for your help on how to display the data for each row

Feb
13
5 months ago
Activity icon

Replied to How Get Value From Dynamic Fields?

hello @sinnbeck on my table modify this:


                       <td><button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus-square"></i></button></td> 
                    

For this

    <td><button type="button" name="add"  class="btn btn-success add-button"><i class="fa fa-plus-square"></i></button></td>

and in my script change this:

  $("#add").click(function(){

For this:

  $(".add-button").click(function(){

I still can't show the second tool associated with my piece, I just show the first tool

Activity icon

Replied to How Get Value From Dynamic Fields?

hello @a4ashraf the changes applied are not working the truth that is frustrating me, I can not find a solution until here all my changes, you can check it

Table

  <tr>   
                    @foreach ($piece->tools as $p)  
                        <td><input type="text" name="addmore[{{ $loop->index }}][position]" value="{{ $p->position }} " placeholder="Posicion"  class="form-control select2" /></td>                             
                                                  
                        <td><input type="text" name="addmore[{{ $loop->index }}][code_tool]" value="{{ $p->code_tool }}"  placeholder="Herramienta"class="form-control" /></td>      
                        
                        <td><input type="text" name="addmore[{{ $loop->index }}][code_insert]" value="{{ $p->insert->code_insert }}" placeholder="Inserto" class="form-control" /></td>  
                        
                        <td><input type="text" name="addmore[{{ $loop->index }}][quality]" value="{{ $p->insert->quality }}" placeholder="Calidad" class="form-control" /></td>                      
                    
                        <td><button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus-square"></i></button></td>
                    @endforeach 
                    </tr>  

Script

<script type="text/javascript">
   
    // var i = 0;
    var i = $('your-hidden-field').val();
       
    $("#add").click(function(){
   
        ++i;

        $("#dynamicTable").append('<tr><td><input type="text" name="addmore['+i+'][position]" placeholder="Posición" class="form-control"/></td><td><input type="text" name="addmore['+i+'][code_tool]" placeholder="Herramienta" class="form-control" /></td> <td><input type="text" name="addmore['+i+'][code_insert]" placeholder="Inserto" class="form-control" /></td>  <td><input type="text" name="addmore['+i+'][quality]" placeholder="Calidad" class="form-control"/></td><td><button type="button" class="btn btn-danger remove-tr"><i class="fa fa-trash "></i></button></td></tr>');

        $('your-hidden-field').val() = i+1;    
    });
   
    $(document).on('click', '.remove-tr', function(){  
         $(this).parents('tr').remove();
    });  


</script>

I would like to know if an image can be uploaded, the information is but it is not displayed correctly in my table

Feb
12
6 months ago
Activity icon

Replied to How Get Value From Dynamic Fields?

@a4ashraf Modify and correct the changes you indicated to me

  @foreach ($piece->tools as $p)                 

                        <td><input type="text" name="addmore[{{ $p->id }}][position]" value="{{ $p->position }} " placeholder="Posicion"  class="form-control select2" /></td>
   @endforeach                              

I still can't see the second tool I'm missing, I know the data is correct, maybe the problem is in the script of adding dynamic input fields this is my script can you check it?


<script type="text/javascript">
   
    var i = 0;
       
    $("#add").click(function(){
   
        ++i;

        $("#dynamicTable").append('<tr>
<td><input type="text" name="addmore['+i+'][position]" placeholder="Posición" class="form-control"/></td>
<td><input type="text" name="addmore['+i+'][code_tool]" placeholder="Herramienta" class="form-control" /></td>
<td><input type="text" name="addmore['+i+'][code_insert]" placeholder="Inserto" class="form-control" /></td>  <td><input type="text" name="addmore['+i+'][quality]" placeholder="Calidad" class="form-control"/></td><td><button type="button" class="btn btn-danger remove-tr"><i class="fa fa-trash "></i></button></td></tr>');
    });
   
    $(document).on('click', '.remove-tr', function(){  
         $(this).parents('tr').remove();
    });  
   
</script>
Activity icon

Replied to How Get Value From Dynamic Fields?

@a4ashraf Thanks for responding, I am testing with your response and I receive the following error:

ErrorException: Trying to get property &#039;index&#039; of non-object 
   @foreach ($piece->tools as $p)                                                     
                        <td><input type="text" 
                                  name="addmore[{{ $loop->parent->index }}][{{ $loop->index }}][position]" 
                                  value="{{ $p->position }} " 
                                 placeholder="Posicion"  
                                 class="form-control select2" />
                        </td>    
   @endforeach                          
Activity icon

Replied to How Get Value From Dynamic Fields?

@bobbybouwmann I am solving it this way:

  @foreach ($piece->tools as $p)                                 
                        <td><input type="text" name="addmore[0][position]" value="{{ $p->position }}" placeholder="Posicion"  class="form-control select2" /></td>                             
                                                  
                        <td><input type="text" name="addmore[0][code_tool]" value="{{ $p->code_tool }}"  placeholder="Herramienta"class="form-control" /></td>      
                        
                        <td><input type="text" name="addmore[0][code_insert]" value="{{ $p->insert->code_insert }}" placeholder="Inserto" class="form-control" /></td>  
                        
                        <td><input type="text" name="addmore[0][quality]" value="{{ $p->insert->quality }}" placeholder="Calidad" class="form-control" /></td>                      
                    
                        <td><button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus-square"></i></button></td>
                    @endforeach 

It happens that this piece has 2 tools associated so that in my dynamic table it is perfectly completed with its first tool, but the second tool is not shown, it breaks the dynamic table, visually a row is created next to the first row and with all The empty fields.

How to verify how many associated tools each piece has? So I could show all the tools that exist for each piece

Activity icon

Replied to How Get Value From Dynamic Fields?

Hi, @a4ashraf I know you could help me with this problem, because you helped me with the solution of how to save dynamic input fields. Now I am trying to show that dynamic data in my blade file.

Activity icon

Replied to How Get Value From Dynamic Fields?

@bobbybouwmann. Sorry for not being clear. Answering your question: I cannot show the data of each field within my dynamic table. I want to clarify that this table is a dynamic table where I can add as many rows as I want

Feb
11
6 months ago
Activity icon

Started a new Conversation How Get Value From Dynamic Fields?

Within my form I have a dynamic table that allows me to add as many dynamic fields as I want through jquery.

I need to iterate over each field that has an array format and get each value entered in order to edit the information

This dynamic table allows to register the tools that are used for the manufacture of a piece.

So the relationship between Piece and Tool is a many to many relationship. And in turn there is a one-to-many relationship with Insert and Tools

This is my dynamic table in my form:

<div class="box box-primary">
            <div class="box-header with-border">
                <h3 class="box-title">Herramientas</h3>                
            </div>
            <div class="box-body">
                <table class="table table-striped table-bordered table-condensed table-hover" id="dynamicTable">  
                    <tr>
                        <th width="5%">Posición</th>
                        <th width="20%">Herramienta</th>                 
                        <th width="20%">Inserto</th>                 
                        <th width="20%">Calidad</th>                 
                        <th width="5%">Action</th>
                    </tr>
                    <tr>
                        <td><input type="text" name="addmore[0][position]"  placeholder="Posicion" class="form-control select2" /></td>                             
                        <td><input type="text" name="addmore[0][code_tool]"   placeholder="Herramienta" class="form-control" /></td>      
                        <td><input type="text" name="addmore[0][code_insert]"  placeholder="Inserto" class="form-control" /></td>  
                        <td><input type="text" name="addmore[0][quality]"  placeholder="Calidad" class="form-control" /></td>                      
                        <td><button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus-square"></i></button></td>                    
                    </tr>  
                </table> 
            </div>
        </div>

This is my edit method: With this I have all the information I need to recover ('piezas' => Piece::with(['tools.insert'])->get(),)

public function edit($id)
    {          
        $piece = Piece::findOrFail($id);  
        
        return view('admin.pieces.partials.form', [  
            'piezas'        => Piece::with(['tools.insert'])->get(),       
            'part_piece'    => Piece::pluck('part_piece', 'part_piece'), 
            'denomination'  => Piece::pluck('denomination', 'denomination'), 

            'type_gag'      => Gag::pluck('type_gag', 'type_gag'),           
            'category_gag'  => Gag::pluck('category_gag', 'category_gag'), 
           
            'part_program'  => Program::pluck('part_program', 'part_program'),                      
            'piece'         => $piece
        ]);  
    }

this doesn't work for me:

@foreach ($piezas as $pieza)
                        @foreach ($pieza->tools as $tool)         
                        <td><input type="text" name="addmore[0][position]" value="{{ $tool['position'] }}" placeholder="Posicion"  class="form-control select2" /></td>                             
                        <td><input type="text" name="addmore[0][code_tool]" value="{{ $tool['code_tool'] }}"  placeholder="Herramienta"class="form-control" /></td>      
                        <td><input type="text" name="addmore[0][code_insert]" value="{{ $tool->insert['code_insert'] }}" placeholder="Inserto" class="form-control" /></td>  
                        <td><input type="text" name="addmore[0][quality]" value="{{ $tool->insert['quality'] }}" placeholder="Calidad" class="form-control" /></td>                      
                        <td><button type="button" name="add" id="add" class="btn btn-success"><i class="fa fa-plus-square"></i></button></td>
                    
                        @endforeach                        
                     
                        @endforeach

How to navigate these fields in array format?

Feb
10
6 months ago
Activity icon

Replied to How To Save BelongsToMany Relationship In Laravel?

@a4ashraf thanks for your answer I was able to save a piece with all its tools helped me solve my problem

Feb
09
6 months ago
Activity icon

Replied to How To Save BelongsToMany Relationship In Laravel?

@a4ashraf Thanks for your answer later I try it and I comment the solution

Activity icon

Replied to How To Save BelongsToMany Relationship In Laravel?

hola @a4ashraf make the modification you just indicated, make a new test by creating a new piece with 2 different tools, when saving them in my pivot table piece_tool I only see the piece created associated with a single tool, (another one is missing) that is why I am Thinking that my problem is here:

 $addmore = $request->addmore;

                foreach($addmore as $add)
                {
                    $insert = Insert::create([
                        'code_insert' => $add['code_insert'],
                        'quality'     => $add['quality']
                    ]);  
                   
                    $tools = $insert->tools()->create([
                        'position'   => $add['position'],
                        'code_tool'  => $add['code_tool'],                   
                        'insert_id'  => $insert->id                            
                    ]);                
                    dd($tools);
                }

checking with dd($tools); i get this

#attributes: array:6 [
    "position" => "01"
    "code_tool" => "cod56"
    "insert_id" => 54
    "updated_at" => "2020-02-09 08:59:17"
    "created_at" => "2020-02-09 08:59:17"
    "id" => 50
  ]
  #original: array:6 [
    "position" => "01"
    "code_tool" => "cod56"
    "insert_id" => 54
    "updated_at" => "2020-02-09 08:59:17"
    "created_at" => "2020-02-09 08:59:17"
    "id" => 50
  ]

I enter two different tools, but I receive two identical tools. I think I'm close to being able to do it I need your help