Update dateTime column with laravel - mysql

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!

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>

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

Related

Auto-refresh div containing Google map with Laravel

I have a div containing a map from Google in a Laravel view, this view receives a JSON array containing coordinates from a MySQL database to insert markers on the map, and I want the div to refresh automatically after a certain amount of time in case a new record is entered on the database.
index function from the controller that sends the array when the view first loads:
public function index()
{
if (Auth::guest())
{
return redirect('home');
}
else{
$user = Auth::user();
$data = Reading::where('reg_id', $user->regNumber)->get();
return view('readings.index', ['data'=>$data]);
}
}
After the page loads, another function is prepared to start refreshing the div:
$(document).ready(function(){
setInterval(function(){
$('#map').load('refresh',function () {
initMap(); //function that generates map with markers
});
},20000);
});
This calls another function from the controller:
public static function refresh()
{
$user = Auth::user();
$data = Reading::where('reg_id', $user->regNumber)->get();
return response()->json(['data'=>$data]);
}
It goes ok when the page loads, but when the div refreshes for the first time I get a warning from the browser's inspector: "[Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/." and I see the array get sent multiple times.
Obviously my idea is problematic, so I'm trying to find a way to do it properly.
I think best way it will be over ajax request.
Ajax request can return html so you will call ajax take response and put it inside "old" div.

Keyup event fire multipletime

Currently, I am working on Angular 4 app. In my component Html, I have one textbox. Whenever user first type anything I want to make an API call to get some data.
The issue is if User type 'A' then it is working fine and calling API. But when user type "ABC" it is making API call 3 times. Instead of making API call for every letter, only one call should be made.
Please suggest any solution.
Component's HTML :
<input id="inputbox" (keyup)="keyUp($event)"/>
Component :
data: string[]
keyUp(event: any) {
this.loadDataApiCall();
}
loadDataApiCall() {
// calling api to load data.
//fill data into
}
Can I solve this issue with help of RXjs in angular 4
Observable.fromEvent(yourDomElement, 'keyup').auditTime(100).subscribe(()=>{
doSomething();
});
You should probably add a timeout to your call and clear it every time it is triggered so only the last call is called.
data: string[]
keyUp(event: any) {
window.clearTimeout(window.apiCallTimeout);
window.apiCallTimeout = window.setTimeout(this.loadDataApiCall, 100);
}
loadDataApiCall() {
// calling api to load data.
//fill data into
}
This means of course that the call will be done 100ms after the user stops typing. Also if he types "a" and after a while he types "bc", then two calls will be made. Of course you can increase the delay to meet your requirements.
If you only want one API call you can use the blur event, which is emitted when the control loses focus:
<input id="inputbox" (blur)="keyUp($event)"/>
Try this:
keyUp(event: any) {
this.loadDataApiCall();
event.stopImmediatePropagation();
}
the right way to implement this is by registering the event and calling the API after sometime while saving the latest value and checking that the last registered value matches the latest registered value
so in your keyup
keyUp(event: any) {
this.latestValue = event.target.value;
this.registerApiCall(event.target.value);
}
register func
registerApiCall(value){
setTimeout(this.loadDataApiCall.bind(this), 500, value)
}
api call
loadDataApiCall(value) {
if (this.latestValue == value ){
// calling api to load data.
//fill data into
}
}
see working example in this plnk
EDIT:
Observable.fromEvent(yourDomElement, 'keyup').auditTime(100).subscribe(()=>{
doSomething();
});
by é™ˆæšćŽ is the RxJs implementation that looks much better, and here is a working plnkr
If you're willing to change your form to Reactive Forms this would be extremely easy
this.form.get("input").valueChanges.debounceTime(1000).subscribe((value) => {});
Reactive Forms gives you access to observables of value changes and status changes. We're basically subscribing to that observable which emits the value any time it changes and we add a delay of one second so that if the user is still typing and changing the value then it will not execute the code in our subscribe.
#Component({
selector: 'my-app',
template: `
<div>
<input type="text" (keyup)='keyUp.next($event)'>
</div>
,
})
export class App {
name:string;
public keyUp = new Subject<string>();
constructor() {
const subscription = this.keyUp
.map(event => event.target.value)
.debounceTime(1000)
.distinctUntilChanged()
.flatMap(search => Observable.of(search).delay(500))
.subscribe(console.log);
}
}

In a <form onSubmit={}>, is the event data automatically passed?

I'm following along with a React tutorial on Thinkster and noticed that the form has an onSubmit tag, which automatically passes on the event to be intercepted.
I did some quick research and couldn't seem to find any indication that this is normally what happens on an onSubmit. Am I missing something here? I just found it rather curious.
From CommentInput.js
...
this.createComment = ev => {
ev.preventDefault();
const payload = agent.Comments.create(this.props.slug, {body: this.state.body});
this.setState({body: ''});
this.props.onSubmit(payload);
};
}
render() {
return (
<form className="card comment-form" onSubmit={this.createComment}>
...
}
Thanks!
inside constructor() method declare
this.createComment= this.createComment.bind(this); to remove auto submiting if it is the case of your question. But if you are asking that, are the data passed when you click submit button, then yes. They should be sent.

Save car id into html

I working with Laravel, with blade views.
I have an array of cars. The user can choose one car from the list, each user can only show his list.
After selecting a car, a modal view appears into the same HTML for showing more information about the car.
If the user wants to remove the car, a post request is called, and HERE is the problem.
How can I pass to the modal, the id of the car that he selected? Because I need it for the post request if he wants to delete the car for example. May be save into variable.
I know how to pass parameter to the modal and then show it into "h3" or "inputs"but this id I can't show him, also he can't change it because he can modify it to remove another car from the list.
Thanks for help
I think i understand what you need, so you have a main controller
public function cars()
{
$cars = Cars::all();
return view('cars',compact('cars'))
}
Then what you can do if you a view single car or delete you can pass the model.
public function single(Cars $cars)
{
return view('single',compact('cars'))
}
Your routes willl look like this
Route::get('cars',['uses' => 'CarsController#cars','as' => 'cars.all']);
Route::get('cars/{cars}',['uses' => 'CarsController#single' => 'as' => 'cars.single']);
and your HTML will be
{{$car->name}}
Hope this helps?
If you was posting via Ajax you would do something like this.
#foreach($cars as $car)
<tr>
<td>{{$car->name}}</td>
<td><a class="view" href="#" data-id="{{$car->id}}">View</a></td>
</tr>
#endforeach
<script>
$('.view').click(function() {
var car = $(this);
var car_id = car.data('id');
$.ajax({
url: '/car/single'+car_id,
type: 'get',
success: function(data) {
$('#details').html(data);
}
});
});
</script>
Will use the same controller:
public function single(Cars $cars)
{
return $cars;
}

Can't post value back to action Method using #Html.BeginForm

I have some code, where when the user clicks on the "x" icon then call the CancelPendingQuote action method passing along the requestId in the requestUrl. The action method is hitting but the value is not included in the requestIdEncrypted parameter, thus the action method parameter has a null value.
Pending List
#using (#Html.BeginForm("CancelPendingQuote", "Quote", new { requestIdEncrypted = request.RequestIdEncrypted }, FormMethod.Get, new { enctype = "multipart/form-data", #id = "removeRequest" }))
{
<span data-bind="click: function(data, event){ userWarning_Dialog('#removeRequest_dialog', event); }">
<img src="~/Areas/Waybill/Content/Images/Normal_Size/posta_delete_20px.png" />
<img src="~/Areas/Waybill/Content/Images/Normal_Size/posta_delete_mouseover_20px.png" style="display:none" />
</span>
}
Knockout userWarning function that submits the form. This is called when image "x" is clicked.
removeRequest: function (model, event)
{
var form = $("#removeRequest").closest("form");
$(form).submit().error(function (messageObj) {
// if fail return error message
$(".information-bar").trigger("ErrorText", messageObj.message);
});
$("#removeRequest_dialog").dialog("close");
},
Action method
[Authorize]
public ActionResult CancelPendingQuote(string requestIdEncrypted)
{
int requestId = Convert.ToInt16(Decryption.Decrypt(requestIdEncrypted));
_controllerContent.QuoteService.Value.CancelPendingQuoteRequest(requestId);
return RedirectToAction("Dashboard");
}
Any Ideas?
There's a couple things here. For one, you need to make sure that the names of the object being posted to the server match up with the Controller's parameter. For instance, if you send this Javascript object up:
{ requestIdEncrypted: "exampleString" }
or
{ requestIdEncrypted: viewModel.requestId() }
then your Controller method should accept the input.
Secondly, from your code it's not evident to me how the data is being posted. $(form).submit().error(function (messageObj) is a little confusing: is this line responsible for submitting the form? Is it a function that would be called if the form submission is unsuccessful? Is it working? It's not clear to me what you're trying to do with this. You may have to figure out another way to attach an error handler to the form, if this is what you're trying to do - unless it's working alright.