Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update dateTime column with laravel

I have a pins table in my database with a pin_date column.

In my migration I have this:

$table->dateTime('pin_date')->nullable();

I have a button that points to a post route

Route::post('/pins/pin-date/{id}', 'PinsController@pinDate');

that leads to a pinDate controller method:

public function pinDate($id)
{
    $pin = Pin::find($id);

    $pin->save();
}

I want to update the pin-date column in the database to the current date and time when I click the button and hit the route. I am not really sure how to do this. Any help would be greatly appreciated! Thank you!

like image 936
L. Fox Avatar asked Apr 06 '18 19:04

L. Fox


2 Answers

I would do this whenever the model is saving, you can bind to the boot function of the model and set it there:

public static function boot()
{
    parent::boot();

    static::saving(function($pin) {
        $pin->pin_date = \Carbon::now()
    });
}

If you want to update this value instead of handling it whenever the model is saved - such as through a button click, you can use Ajax. You will need 1.) a route, 2.) a click handler, 3.) an AJAX request and 4.) a controller to handle processing the request:

Click handler with Ajax:

$('.btn').on('click', function(e) {
    $.ajax({
        url: '/route/to/update/my/pin' + $(this).closest('.pin').data('id')
    });
});

Then a route:

Route::post('/route/to/update/my/pin/{id}', 'PinController@updatePinDate');

Then make the controller method and update it accordingly:

public function updatePinDate(Request $request, Pin $pin)
{
    $pin->pin_date = \Carbon::now();
    $pin->save();
}

If you don't want to use javascript, you can just use a standard form with the same route/controller methods:

<form action="/route/to/update/my/pin/{{ $pin->id }}" method="POST">
     {{csrf_field()}}

     <button type="Submit"> Update Pin Date </button>
</form>
like image 75
Ohgodwhy Avatar answered Oct 20 '22 01:10

Ohgodwhy


public function pinDate($id)
{
    $pin = Pin::find($id);
    $pin->pin_date = \Carbon\Carbon::now();
    $pin->save();
}

I hope it works.

like image 20
Marlon Adarme Avatar answered Oct 19 '22 23:10

Marlon Adarme