palla451

palla451

Member Since 2 Years Ago

Rome

Experience Points
4,470
Total
Experience

530 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
28
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
4,470 XP
Apr
07
2 days ago
Activity icon

Replied to Confusion About Redis And Laravel

I used the function


function showProfile($id)
 {
        // Check if user already in redis with cache key user.1 for example
        if (!Redis::exists('user.' . $id)) {
            // If the user is not in redis, fetch it from DB and add it in redis for 60 seconds before returning it
            $user = User::findOrFail($id);
            Redis::set('user.' . $user->id, $user);

            return $user;
        } 

            // If user is in redis, just return it without querying the database
            return Redis::get('user'.$id);// How to set this?
}

@etiennedeschenes in console of redis, if I throw GET user.1 i have the user with id 1, but in laravel i have a value null why?

Edit: sorry my error return Redis::get('user.'.$id);

It's work fine!

Activity icon

Replied to Confusion About Redis And Laravel

I forgot to tell you that I had set Redis to .env.

Thank you @etiennedeschenes

Apr
06
3 days ago
Activity icon

Replied to Confusion About Redis And Laravel

@etiennedeschenes thanks you. But i wish to use Redis for exercise....

Activity icon

Started a new Conversation Confusion About Redis And Laravel

I followed the laravel documentation

database.php

'redis' => [

        'client' => env('REDIS_CLIENT', 'predis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],

        'cache' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CACHE_DB', '1'),
        ],

    ],

web.php

Route::get('/' ,'[email protected]');
Route::get('/showprofile/{id}' ,'[email protected]');
UsersController

    /**
     * @param $id
     * @return mixed
     */
    public function showProfile($id)
    {
        $user = Redis::get('user:profile:'.$id);// How to set this?
        
        return view('user.profile', compact('user'));
    }

user.profile.blade



	{{ $user->name }}

Have error:

Trying to get property 'name' of non-object 

Mar
31
1 week ago
Activity icon

Started a new Conversation Homestead Public_network Problem

Hi all, i have this Homestead.yml :

---
ip: "192.168.10.10"
memory: 2048
cpus: 1
provider: virtualbox

authorize: ~/.ssh/id_rsa.pub

keys:
    - ~/.ssh/id_rsa

folders:
    - map: .
      to: /home/vagrant/code

sites:
    - map: homestead.local
      to: /home/vagrant/code/public
      php: "7.3"

    - map: phpmyadmin.local
      to: /home/vagrant/code/phpmyadmin/

    - map: laravel.local
      to: /home/vagrant/code/laravel/public
      php: "7.3"

    - map: passport.local
      to: /home/vagrant/code/passport/public
      php: "7.3"

    - map: crm_test.local
      to: /home/vagrant/code/crm_test/public
      php: "7.3"
     
    - map: contabilita.local
      to: /home/vagrant/code/contabilita/public
      php: "7.3"
     
    - map: test.local
      to: /home/vagrant/code/test/public
      php: "7.3"
   
    - map: bookkeeping.local
      to: /home/vagrant/code/bookkeeping/public
      php: "7.3"
     
    - map: accounting_system.local
      to: /home/vagrant/code/accounting_system/public
      php: "7.3"
      
      
databases:
    - homestead
    - passport
    - new_release
    - crm_test
    - phpmyadmin
    - contabilita
    - test
    - bookkeeping
    - accounting_system
    
networks:
    - type: "public_network"
      ip: "192.168.10.20"
      bridge: "en1: Wi-Fi (AirPort)"

# ports:
#     - send: 50000
#       to: 5000
#     - send: 7777
#       to: 777
#       protocol: udp

# blackfire:
#     - id: foo
#       token: bar
#       client-id: foo
#       client-token: bar

# zray:
#  If you've already freely registered Z-Ray, you can place the token here.
#     - email: [email protected]
#       token: foo
#  Don't forget to ensure that you have 'zray: "true"' for your site.

When i connect from my lan with another device to 192.168.10.20 i show only the site accounting_system, what should I do to browse other sites?

Mar
30
1 week ago
Activity icon

Replied to Refresh LaravelChart Without Reloading The Page

Of course

{{ $chart->id }}_refresh(original_api_url + "?date_start=2019-01-01&date_end=2019-12-31"); 

but in my case it's a refresh update on himself

Activity icon

Started a new Conversation Refresh LaravelChart Without Reloading The Page

I have a view with a chart created with LaravelChart and in the same view I have a table created with DataTable. I would like adding a data in the table to update the chart through ajax

    <input type="hidden" id="char_api" value="{{ $chart->id }}_api_url" />
    <input type="hidden" id="char_id" value="{{ $chart->id }}" />
    <div id="jumbotron" style="width: 100%">
        {!! $chart->container() !!}
    </div>


<h1>Inputs</h1>
<a class="btn btn-success" href="javascript:void(0)" id="createNewRecord">Insert new Input</a>
<table class="table table-bordered data-table" width="100%" data-route="{{ route('inputs.index') }}">
    <thead>
    <tr>
        <th>No</th>
        <th>Description</th>
        <th>Payment</th>
        <th>Import</th>
        <th>Date</th>
        <th width="280px">Action</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<div class="modal fade" id="ajaxModel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"></h4>
            </div>
            <div class="modal-body">
                <form id="addRecord" name="addRecord" class="form-horizontal">


                    <input type="hidden" name="record_id" id="record_id">

                    <div class="form-group">
                        <label for="description" class="col-sm-2 control-label">Descriptions</label>
                        <div class="col-sm-12">
                            <textarea id="description" name="description" required="" placeholder="Enter Description" class="form-control" required></textarea>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="import" class="col-sm-2 control-label">Import</label>
                        <div class="col-sm-12">
                            <input type="text" id="import" name="import" required="" placeholder="Es. 12,58" class="form-control" required />
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">Payment</label>
                        <div class="col-sm-12">
                            <select class="form-control" name="payment" id="payment">
                                @foreach($payments as $payment)
                                    <option value="{{ $payment->id }}">{{ $payment->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">Date</label>
                        <div class='col-sm-12'>
                            <div class="input-group-prepend">
                                <input class="form-control" name="date" placeholder="dd-mm-yyyy" type="text"  id="datepicker" />
                            </div>
                        </div>
                    </div>

                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="button" class="btn btn-secondary"  data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary" id="saveBtn" value="create">Send</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>




<script src="{{ asset('js/ajaxController.js') }}"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js" charset="utf-8"></script>
{!! $chart->script() !!}

ajaxController.js


$(function () {

    var route = $('.table').data('route');
    var char_id = $('#char_id').val();
    var char_api = $('#char_api').val();
    console.log(char_id);
    console.log(char_api);


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

    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: route,
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'description', name: 'description'},
            {data: 'payment', name: 'payment'},
            {data: 'import', name: 'import'},
            {data: 'date', name: 'date'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });

    $('#createNewRecord').click(function () {
        $('#saveBtn').val("create-input");
        $('#record_id').val('');
        $('#addRecord').trigger("reset");
        $('#modelHeading').html("Create New Input");
        $('#ajaxModel').modal('show');
    });

    $('body').on('click', '.editRecord', function () {
        var record_id = $(this).data('id');

        $.get(route + '/' + record_id + '/edit', function (data) {
            var dateCovert = convertDateTostring(data.date);
            $('#record_id').val(data.record_id);
            $('#modelHeading').html("Edit Input");
            $('#saveBtn').val("edit-input");
            $('#ajaxModel').modal('show');
            $('#record_id').val(record_id);
            $('#description').val(data.description);
            $('#payment').val(data.payments[0].id);
            $('#import').val(data.import);
            $('#datepicker').val(dateCovert);
        })
    });

    $('#saveBtn').click(function (e) {
        e.preventDefault();
        $(this).html('Sending..');
        $.ajax({
            data: $('#addRecord').serialize(),
            url: route,
            type: "POST",
            dataType: 'json',
            beforeSend: function () {
                $('#ajaxModel').modal('hide');
                $(".se-pre-con").css("opacity", 0.5).show();
            },
            success: function (data) {
                $(".se-pre-con").delay(2000).fadeOut();
                $('#addRecord').trigger("reset");
                $('#saveBtn').html('Send');
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
                alert('Ops, qualcosa è andato storto.....');
                $(".se-pre-con").delay(2000).fadeOut();
            }
        });
    });

    $('body').on('click', '.deleteRecord', function () {
        var record_id = $(this).data("id");
        if(confirm("Are You sure want to delete !")){
            $.ajax({
                type: "DELETE",
                url: route + '/' + record_id,
                beforeSend: function () {
                    $(".se-pre-con").css("opacity", 0.5).show();
                },
                success: function (data) {
                    $(".se-pre-con").delay(2000).fadeOut();
                    table.draw();
                },
                error: function (data) {
                    console.log('Error:', data);
                }
            });
        };

    });

});

function convertDateTostring(dateConvert) {
    var dateConvert = dateConvert.toString().slice(0,10);
    var dateSplit = dateConvert.split('-');
    var newDate = dateSplit[2] + '-' + dateSplit[1] + '-' + dateSplit[0];
    return newDate;
}

InputsController



public function chart($user)
{
    $lastMounthInput = Input::whereDate('date','>=', Carbon::now()->subDays('30'))
                            ->where('user_id', '=', $user->id)
                            ->orderBy('date','asc')
                                 ->get()
                                ->groupBy(function($input) {
                                    return Carbon::parse($input->date)->format('d-m');
                    });

    $mounthInput = $lastMounthInput->map(function ($result) {
                    return number_format((float)$result->sum('import_as_float'), 2, '.', '');
                });

    $chart = new InputChart();
    $chart->labels($mounthInput->keys());
    $chart->dataset('Last Mounth Input','bar' , $mounthInput->values())
                ->backgroundColor('rgb(0,123,255)');

    return $chart;

}

public function getQueryChart($user)
{
    $lastMounthInput = Input::whereDate('date','>=', Carbon::now()->subDays('30'))
        ->where('user_id', '=', $user->id)
        ->orderBy('date','asc')
            ->get()
                ->groupBy(function($input) {
                    return Carbon::parse($input->date)->format('d-m');
        });

    $mounthInput = $lastMounthInput->map(function ($result) {
        return number_format((float)$result->sum('import_as_float'), 2, '.', '');
    });

    return $mounthInput;
}




/**
 * Function for test ChartTv
 */
public function chartApi(Request $request) {

    $test = $request->all();

    $user = Auth::user();
    $chart = new InputChart();
    $mounthInput = $this->getQueryChart($user);
    $chart->dataset('Last Mounth Input', 'line', $mounthInput->values())
                        ->backgroundColor('rgb(0,123,255)');
    return json_decode($chart->api());
}

How do I refresh the chart by calling Ajax without reloading the page by pressing the btnSave button, please.

Thanks all...

Activity icon

Replied to LarvelChart Error With Api Chart

i resolved with

return json_decode($chart->api());

Mar
27
1 week ago
Activity icon

Replied to Laravel Charts Ajax And Csrf

@deansatch i

I solved it changing return $chart->api(); with return json_decode($chart->api());

Activity icon

Started a new Conversation LarvelChart Error With Api Chart

Hi, all

I have been trying to resolve this problem for a few days

In my laravel project I installed the LaraceverCharts/Tv package.

API/Ajax Charts for reload and refresh the chart i have API/Ajax Charts following the guide:

2 Route:


Route::get('chartData','[email protected]');
Route::get('chartApi', '[email protected]');

In My controller


    /**
     * Function for test ChartTv
     */
    public function chartData()
    {
        $chart = new InputChart();

        $api = url('/chartApi');

        $chart->labels(['test1', 'test2', 'test3'])
            ->load($api);

        return view('chart',compact('chart'));
    }

    public function chartApi() {
        $chart = new InputChart();
        $chart->dataset('Sample Test', 'bar', [3,4,1]);
        $chart->dataset('Sample Test', 'line', [1,4,3]);
        return $chart->api();
    }

In my chart.blade

<div id="container">
    {!! $chart->container() !!}
</div>
<script src=https://cdnjs.cloudflare.com/ajax/libs/echarts/4.0.2/echarts-en.min.js charset=utf-8></script>
{!! $chart->script() !!}

I don't understand how to refresh or reload or view the page , i have same this error:

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 138

Mar
26
2 weeks ago
Activity icon

Replied to Sum Of Collection After A GroupBy

I have an existing database and I would not like to change the data entry of import field.

@tykus your solution is really very good, thank you very much

Activity icon

Started a new Conversation Sum Of Collection After A GroupBy

hi guy, i have this query:


$inputMounth = Input::whereDate('date','>=', Carbon::now()->subDays('30'))
                                ->orderBy('date','asc')->get()
                                     ->groupBy('date');

and this is the result


{
2020-03-16: [
{
id: 2,
user_id: 1,
description: "Enel",
import: "678",
date: "2020-03-16",
created_at: "2020-03-24T10:53:06.000000Z",
updated_at: "2020-03-24T10:53:06.000000Z"
}
],
2020-03-23: [
{
id: 3,
user_id: 1,
description: "pippo",
import: "16,78",
date: "2020-03-23",
created_at: "2020-03-24T13:51:27.000000Z",
updated_at: "2020-03-24T13:51:27.000000Z"
}
],
2020-03-24: [
{
id: 1,
user_id: 1,
description: "Gas",
import: "169,78",
date: "2020-03-24",
created_at: "2020-03-24T10:50:57.000000Z",
updated_at: "2020-03-24T10:50:57.000000Z"
},
{
id: 4,
user_id: 1,
description: "Ciccio",
import: "198,78",
date: "2020-03-24",
created_at: "2020-03-24T14:24:58.000000Z",
updated_at: "2020-03-24T14:24:58.000000Z"
},
{
id: 5,
user_id: 1,
description: "test",
import: "90",
date: "2020-03-24",
created_at: "2020-03-24T15:11:47.000000Z",
updated_at: "2020-03-24T15:11:47.000000Z"
}
]
}

I would like to get the total import for everyday. I tried this, but it doesn't work



$inputRes = $inputMounth->map(function ($result, $key) {
                        return [$key => $result->sum('import')];
        });

the "import" is a string so it would go to a float

how can I do, please?

Mar
23
2 weeks ago
Activity icon

Replied to Yaira DataTable Insert Not Inline

@nakov thank you very much, sorry for my noob question .....

Mar
22
2 weeks ago
Activity icon

Started a new Conversation Yaira DataTable Insert Not Inline

Hi all, i have this template

in my dashboard.blade.php in section content

@section('content')

<h1>Inputs</h1>
<a class="btn btn-success" href="javascript:void(0)" id="createNewInput">Insert new Input</a>
<table class="table table-bordered data-table" width="100%">
    <thead>
    <tr>
        <th>No</th>
        <th>Description</th>
        <th>Payment</th>
        <th>Import</th>
        <th>Date</th>
        <th width="280px">Action</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<div class="modal fade" id="ajaxModel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"></h4>
            </div>
            <div class="modal-body">
                <form id="addInput" name="addInput" class="form-horizontal">
                    <input type="hidden" name="input_id" id="input_id">

                    <div class="form-group">
                        <label for="description" class="col-sm-2 control-label">Descriptions</label>
                        <div class="col-sm-12">
                            <textarea id="description" name="description" required="" placeholder="Enter Description" class="form-control" required></textarea>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="import" class="col-sm-2 control-label">Import</label>
                        <div class="col-sm-12">
                            <input type="text" id="import" name="import" required="" placeholder="Es. 12,58" class="form-control" required />
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">Payment</label>
                        <div class="col-sm-12">
                            <select class="form-control" name="payment" id="payment">
                                @foreach($payments as $payment)
                                    <option value="{{ $payment->id }}">{{ $payment->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">Date</label>
                        <div class='col-sm-12'>
                            <div class="input-group-prepend">
                                <input class="form-control" name="date" placeholder="dd-mm-yyyy" type="text"  id="datepicker" />
                            </div>
                        </div>
                    </div>

                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <button type="submit" class="btn btn-primary" id="saveBtn" value="create">Send</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

@endsection

if i insert the javascript ajax call inline no error

@section('scripts')

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

    var table = $('.data-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('inputs.index') }}",
        columns: [
            {data: 'DT_RowIndex', name: 'DT_RowIndex'},
            {data: 'description', name: 'description'},
            {data: 'payment', name: 'payment'},
            {data: 'import', name: 'import'},
            {data: 'date', name: 'date'},
            {data: 'action', name: 'action', orderable: false, searchable: false},
        ]
    });

    $('#createNewInput').click(function () {
        $('#saveBtn').val("create-input");
        $('#input_id').val('');
        $('#addInput').trigger("reset");
        $('#modelHeading').html("Create New Input");
        $('#ajaxModel').modal('show');
    });

    $('body').on('click', '.editInput', function () {
        var input_id = $(this).data('id');

        $.get("{{ route('inputs.index') }}" +'/' + input_id +'/edit', function (data) {
            var dateCovert = convertDateTostring(data.date);
            $('#input_id').val(data.input_id);
            $('#modelHeading').html("Edit Input");
            $('#saveBtn').val("edit-input");
            $('#ajaxModel').modal('show');
            $('#input_id').val(input_id);
            $('#description').val(data.description);
            $('#payment').val(data.payments[0].id);
            $('#import').val(data.import);
            $('#datepicker').val(dateCovert);
        })
    });

    $('#saveBtn').click(function (e) {
        e.preventDefault();
        $(this).html('Sending..');
        var input = $(this).data("id");
        $.ajax({
            data: $('#addInput').serialize(),
            url: "{{ route('inputs.store') }}",
            type: "POST",
            dataType: 'json',
            beforeSend: function(){
                $('#ajaxModel').modal('hide');
                $(".se-pre-con").css("opacity", 0.5).show();
            },
            success: function (data) {
                $(".se-pre-con").delay(2000).fadeOut();
                $('#addInput').trigger("reset");
                $('#saveBtn').html('Send');
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
                alert('Ops, qualcosa è andato storto.....')
            }
        });
    });

    $('body').on('click', '.deleteInput', function () {

        var product_id = $(this).data("id");
        confirm("Are You sure want to delete !");

        $.ajax({
            type: "DELETE",
            url: "{{ route('inputs.store') }}"+'/'+product_id,
            beforeSend: function(){
                $(".se-pre-con").css("opacity", 0.5).show();
            },
            success: function (data) {
                $(".se-pre-con").delay(2000).fadeOut();
                table.draw();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });

});
function convertDateTostring(dateConvert) {
    var dateConvert = dateConvert.toString().slice(0,10);
    var dateSplit = dateConvert.split('-');
    var newDate = dateSplit[2] + '-' + dateSplit[1] + '-' + dateSplit[0];
    return newDate;
}

@endsection

If i insert the javascript in an external file ajaxInput.js in public/js folder

@section('scripts')

    <script src="{{ asset('js/ajaxInput.js').time() }}"></script>

@endsection

i have this error

DataTables warning: table id=DataTables_Table_0 - Ajax error.

Why?

Mar
21
2 weeks ago
Activity icon

Awarded Best Reply on Update Pivot Table Of Many To Many Polimorph Relationship

I resolve in update


$input->payments()->detach();
$input->payments()->attach($request->payment,[
                'paymentable_id' => $request->input_id,
                'paymentable_type' => 'App\Models\Input']);

return response()->json(['success'=>'Product saved successfully.']);

But I don't know if it's the best result

Mar
20
2 weeks ago
Activity icon

Replied to Update Pivot Table Of Many To Many Polimorph Relationship

I resolve in update


$input->payments()->detach();
$input->payments()->attach($request->payment,[
                'paymentable_id' => $request->input_id,
                'paymentable_type' => 'App\Models\Input']);

return response()->json(['success'=>'Product saved successfully.']);

But I don't know if it's the best result

Activity icon

Replied to Update Pivot Table Of Many To Many Polimorph Relationship

Input Model


    protected $fillable = [
         'name', 'money' 
    ];

    /**
     * Get all of payments method.
     */
    public function payments()
    {
        return $this->morphToMany(Payment::class, 'paymentable');
    }

Output Model


    protected $fillable = [
         'name', 'money' 
    ];

    /**
     * Get all of payments method.
     */
    public function payments()
    {
        return $this->morphToMany(Payment::class, 'paymentable');
    }

Payment Model


    protected $fillable = [
        'name'
    ];

    /**
     * Get all of the inputs that are assigned this tag.
     */
    public function inputs()
    {
        return $this->morphedByMany(Payment::class, 'paymentable');
    }
Activity icon

Started a new Conversation Update Pivot Table Of Many To Many Polimorph Relationship

Hi guys, i all this situation:

3 Tables

inputs


-id
-name
-money

outputs


-id
-name
-money

payments


-id
-name

paymentables


-payment_id         /* example id of payments*/
-paymentable_id     /* example id of inputs */
-paymentable_type /* example /App/Models/Input */

When update an input, how can i change in pivot table paymentable the payment_id ?

I have tried this way but without success:


$input = Input::with('payments')->find($request->input_id); /* input_id is the id of an Input */
$query = $input->payments()->updateExistingPivot([$request->payment],
                ['paymentable_id' => $request->input_id,
                'paymentable_type' => 'App\Models\Input']);
Mar
19
3 weeks ago
Activity icon

Started a new Conversation Laravel DataTables Ajax Call In Edit Mode

Hi all, i can't get the values ​​in Edit Mode with an ajax call and databales. Only $('#description').val(data.description); in edit return the value

InputsController:


    public function index(Request $request)
    {
        if ($request->ajax()) {
            $data = Input::latest()->with('payments')->get();
            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('action', function($row){

                    $btn = 'Edit';

                    $btn = $btn.' Delete';

                    return $btn;
                })
                ->addColumn('payment', function ($data) {
                    foreach($data->payments as $payments){
                        return $payments->name;
                    }
                })
                ->editColumn('date', function ($data){
                    return date('d-m-yy', strtotime($data->date) );
                })
                ->rawColumns(['action'])
                ->make(true);
        }

        $payments = Payment::all();
        $user = Auth::user();

        return view('layout.dashboard',['payments' => $payments, 'user' => $user]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $myDateTime = DateTime::createFromFormat('d-m-Y', $request->get('date'));
        $newDateString = $myDateTime->format('Y-m-d H:i');
        $input = Input::updateOrCreate([
                'user_id' => 1,
                'description' => $request->description,
                'import' => $request->import,
                'date' => $newDateString
            ]);

        $input->payments()->attach($request->get('payment'),[
            'paymentable_id' => $input->getAttribute('id'),
            'paymentable_type' => 'App\Models\Input']);

        return response()->json(['success'=>'Product saved successfully.']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $input = Input::find($id);
        return response()->json($input);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Input::find($id)->delete();

        return response()->json(['success'=>'Input deleted successfully.']);
    }

Dashboard blade:

<h1>Inputs</h1>
<a class="btn btn-success" href="javascript:void(0)" id="createNewInput">Insert new Input</a>
<table class="table table-bordered data-table" width="100%">
    <thead>
    <tr>
        <th>No</th>
        <th>Description</th>
        <th>Payment</th>
        <th>Import</th>
        <th>Date</th>
        <th width="280px">Action</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>


<div class="modal fade" id="ajaxModel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="modelHeading"></h4>
            </div>
            <div class="modal-body">
                <form id="productInput" name="productInput" class="form-horizontal">
                    <input name="input_id" id="input_id">

                    <div class="form-group">
                        <label for="description" class="col-sm-2 control-label">Descriptions</label>
                        <div class="col-sm-12">
                            <textarea id="description" name="description" required="" placeholder="Enter Description" class="form-control" required></textarea>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="import" class="col-sm-2 control-label">Import</label>
                        <div class="col-sm-12">
                            <input type="text" id="import" name="import" required="" placeholder="Es. 12,58" class="form-control" required />
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">Payment</label>
                        <div class="col-sm-12">
                            <select class="form-control" name="payment" id="payment">
                                @foreach($payments as $payment)
                                    <option value="{{ $payment->id }}">{{ $payment->name }}</option>
                                @endforeach
                            </select>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">Date</label>
                        <div class='col-sm-12'>
                            <div class="input-group-prepend">
                                <input class="form-control" name="date" placeholder="dd/mm/yyyy" type="text"  id="datepicker" />
                            </div>
                        </div>
                    </div>

                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary" id="saveBtn" value="create">Send</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

My scripts inline in this page



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

        var table = $('.data-table').DataTable({
            processing: true,
            serverSide: true,
            ajax: "{{ route('inputs.index') }}",
            columns: [
                {data: 'DT_RowIndex', name: 'DT_RowIndex'},
                {data: 'description', name: 'description'},
                {data: 'payment', name: 'payment'},
                {data: 'import', name: 'import'},
                {data: 'date', name: 'date'},
                {data: 'action', name: 'action', orderable: false, searchable: false},
            ]
        });

        $('#createNewInput').click(function () {
            $('#saveBtn').val("create-input");
            $('#input_id').val('');
            $('#productForm').trigger("reset");
            $('#modelHeading').html("Create New Input");
            $('#ajaxModel').modal('show');
        });

        $('body').on('click', '.editInput', function () {

            var input_id = $(this).data('id');
            $.get("{{ route('inputs.index') }}" +'/' + input_id +'/edit', function (data) {
                $('#modelHeading').html("Edit Input");
                $('#saveBtn').val("edit-input");
                $('#ajaxModel').modal('show');
                $('#input_id').val(data.input_id);
                $('#description').val(data.description);
                $('#payment').val(data.payment.name);
                $('#import').val(data.import);
                $('#date').val(data.date);
            })
        });

        $('#saveBtn').click(function (e) {
            e.preventDefault();
            $(this).html('Sending..');

            $.ajax({
                data: $('#productInput').serialize(),
                url: "{{ route('inputs.store') }}",
                type: "POST",
                dataType: 'json',
                success: function (data) {

                    $('#productForm').trigger("reset");
                    $('#ajaxModel').modal('hide');
                    table.draw();

                },
                error: function (data) {
                    console.log('Error:', data);
                    $('#saveBtn').html('Save Changes');
                }
            });
        });

        $('body').on('click', '.deleteProduct', function () {

            var product_id = $(this).data("id");
            confirm("Are You sure want to delete !");

            $.ajax({
                type: "DELETE",
                url: "{{ route('inputs.store') }}"+'/'+product_id,
                success: function (data) {
                    table.draw();
                },
                error: function (data) {
                    console.log('Error:', data);
                }
            });
        });
});
Mar
17
3 weeks ago
Activity icon

Started a new Conversation How To Pass The Route In Url Parameter In Jquery Ajax Call

Hi all, i have a route in web.php


Route::middleware('auth')
    ->prefix('dashboard')->group(function(){
        Route::post('ajax_input_store','[email protected]')->name('ajax_input_store');
});

In my controller


   public function ajaxInputStore(Request $request)
    {
        $user = Auth::user();

        $myDateTime = DateTime::createFromFormat('d-m-Y', $request->get('date'));
        $newDateString = $myDateTime->format('Y-m-d H:i');


        $input = new Input([
            'user_id' => $user->getAttribute('id'),
            'description' => $request->get('description'),
            'import' => $request->get('importo'),
            'date' =>  $newDateString
        ]);

        $input->save();
        $input->payments()->attach($request->get('payment'),[
            'paymentable_id' => $input->getAttribute('id'),
            'paymentable_type' => 'App\Models\Input']);

        return response()->json(['success'=>'Form Data is successfully Stored']);

    }

dafields.js


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

    $("#addInput").click(function(e) {
        e.preventDefault();

        var description = $("#description").val();
        var importo = $("#import").val();
        var payment = $("#payment").val();
        var date = $("#datepicker").val();

        $.ajax({
            type:'POST',
            data: {
                description: description,
                importo: importo,
                payment: payment,
                date : date
            },
            url:"{{ route('ajax_input_store') }}",
            // url: '/dashboard/ajax_input_store',
            success:function(data) {
                $('#formNewInput').modal("toggle");
                alert('save correctly!...');
                resetMyForm();
            },
            error: function(){
                alert("wrong...!!!");
            }
        });
    });
});


// Form reset function
function resetMyForm(){
    $("#description").val('');
    $("#import").val('');
    $("#payment").val(1);
    $("#datepicker").val('');
}

but i have error because don't read the route correctly.

If i insert


url:"/dashboard/ajax_input_store",

the function correctly and have response 200

Mar
15
3 weeks ago
Activity icon

Replied to Many-To-Many Polimorph Relationship Table Pivot

just for the record

$table->foreign('payable_id')->references('id')->on('inputs');

$table->foreign('payable_id')->references('id')->on('outputs');

generate the exception beacuse :

Integrity constraint violation: 1022 Can't write; duplicate key in table '#sql-4bf_59c'

I found this: https://laracasts.com/discuss/channels/eloquent/polymorphism-why-should-i-violate-database-design?page=1

I found the guy very helpful...

Activity icon

Replied to Many-To-Many Polimorph Relationship Table Pivot

Ok, thanks, but if my table is payments the name of table pivot conventionally is paymentables or payables?

P.S.: sorry if I did not specify that it was a polimorphic relationship Many-To-Many now I change the title of the post

Activity icon

Replied to Many-To-Many Polimorph Relationship Table Pivot

but it's a many-to-many polimorph such as video, post and tag. I would like to know how to name my pivot table

In my case the table:

inputs (posts) output (videos) payments (tags) xxxxx (taggables) ??

Conventionally how i can set the name o table pivot , and in migration how i can se the foreign . Thanks

$table->foreign('input_id')->references('id')->on('inputs'); OK but the same foreign references on id on outputs no?

Activity icon

Replied to Many-To-Many Polimorph Relationship Table Pivot

3 tables, inputs, outputs, payments

Activity icon

Started a new Conversation Many-To-Many Polimorph Relationship Table Pivot

Hi all, i don't understand how to set the correct name of table pivot.

I have a relation many-to-many with this models:

Input:

  • id
  • name

Output:

  • id
  • name

Payments (methods of payment)

  • id
  • name

How can i usually set the name of pivot table?

And how can i set the foreign key in migration for this type of relationship?

Mar
12
4 weeks ago
Activity icon

Started a new Conversation No Load Script In Blade Template

Hi all, i have a dashboard.blade

https://pastebin.com/TF4uSvSJ

a template for new_input

https://pastebin.com/XNtkqvCj

and te form

https://pastebin.com/7fHh4Ke1

But when show the origin page view i don't see the script

   $('#sandbox-container input').datepicker({});
Mar
10
4 weeks ago
Activity icon

Started a new Conversation Polimorph Relationship, Issue

I have 3 Model for money entering and leaving the house.

Model: Input, Output and Payment (it's a list of method of payment).

I have a a Many-To-One payments->inputs and a Many-To-One payments->output

I should create a Polimorph Relationship One-To-Many inverse but i don't understand in this case because I am not in the situation of posts, videos and comments.

Help me please.

EDIT: sorry, I realized that it is a many to many polymorphic relationship...

you can close the post

Activity icon

Replied to Relationship User - Job , Question

You're right, I hadn't thought of that. Thans

Activity icon

Started a new Conversation Relationship User - Job , Question

Hi all, sorry for the stupid question.

Hi have two models User and Job.

One user can have just one job but one job more than one user One-to-many(inverse)

In this case in want configure two entity in this way:

User

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'fstName','lstName','email', 'password','job_id'
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'email_verified_at' => 'datetime',
];

/**
 * The roles that belong to the user.
 */
public function roles()
{
    return $this->belongsToMany(Role::class,'role_user');
}

Job

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name'
];


/**
 * Get the users for the job.
 */
public function users()
{
    return $this->hasMany(User::class);
}

I don't have to define the inverse relationship in User model , i'm right?

/**
 * Get the job of a user.
 */
public function job()
{
    return $this->belongsTo(Job::class);
}
Mar
04
1 month ago
Activity icon

Replied to Custom Namespace For Class User

you are right, I fixed it and executed "composer dump-autoload". It's all right

Activity icon

Replied to Custom Namespace For Class User

i know , but if i not config the folder in classmap the class User don't extends Illuminate\Foundation\Auth\User, consequently don't read the mehtods such as check() or attempt()

Activity icon

Replied to Custom Namespace For Class User

no, but maybe I solved it. Basically I had to map the class map to composer.json and then do on config: cache and config: clear. This thing only happened to me with Laravel v.7 never on old laravel projects

"autoload": {
    "psr-4": {
        "App\": "app/"
    },
    "classmap": [
        "app/models",
        "database/seeds",
        "database/factories"
    ]

I'm not getting any errors, just in the Auth I have a false answer.

Thanks for help @sinnbeck , @snapey

Activity icon

Replied to Custom Namespace For Class User

I followed everything and I modified everything but it is still like the Facade Authenticate is not seen

https://pastebin.com/F9nCsdMA

https://pastebin.com/YbcJUcmB

https://pastebin.com/cBxy4iMD

instead if I leave the user class out then the Authenticate facade acts

Activity icon

Started a new Conversation Custom Namespace For Class User

If i change the directory of my User class in App\Models , the facade Auth::check or Auth::attempt don't work

class User extends Authenticatable {

use Illuminate\Contracts\Auth\MustVerifyEmail; use Illuminate\Database\Eloquent\Model; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable;

use Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name', 'email', 'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password', 'remember_token',
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'email_verified_at' => 'datetime',
];

}