6

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!

L. Fox
  • 328
  • 1
  • 6
  • 20

2 Answers2

9

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>
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
  • Ok and how would I make it so when the button gets clicked it triggers that? – L. Fox Apr 06 '18 at 20:04
  • @L.Fox AJAX. Use Javascript to make a POST request to a route, route that method to a controller. Sorry, I must've missed that. Are you using any javascript frameworrk, or jQuery? – Ohgodwhy Apr 06 '18 at 20:05
  • I actually am fairly new to laravel and have almost no experience with JavaScript so I am not using any JavaScript – L. Fox Apr 06 '18 at 20:08
  • @L.Fox Added all the methods and info you should need to accomplish this, with and without javascript – Ohgodwhy Apr 06 '18 at 20:09
  • 2
    Get rid of the `\Carbon::now();` and use just `now()`. – Brian Lee Apr 07 '18 at 02:57
2
public function pinDate($id)
{
    $pin = Pin::find($id);
    $pin->pin_date = \Carbon\Carbon::now();
    $pin->save();
}

I hope it works.

DevK
  • 9,597
  • 2
  • 26
  • 48
Marlon Adarme
  • 357
  • 4
  • 15