different dates from different views to be displayed in a database in laravel - laravel

I am creating a website that allows books to be loaned out, i have 3 options for the loans which are 1 week, 2 weeks and 4 weeks,when a user clicks a book they will be taken to a details page that will display the 3 loan options, if you click on the 1 week loan you will be taken the one week loan page where you can confirm or cancel the loan, the page looks like this
<?php
use Carbon\Carbon;
?>
#extends('layouts.app')
#section('content')
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><h1>1 Week Loan</h1></div>
<div class="panel-body">
<h4>You have attempted to loan out: </h4>
<h4>{{$book->title}}</h4>
<h4>By: {{$book->author}}</h4>
<br/>
<h4>To agree, press the confirm button, to cancel the loan press the cancel button and you will be returned to the home screen.</h4>
<br/>
<form action="{{url('loan')}}" method="POST">
{{ csrf_field() }}
<input type="hidden" name="l_userid" value="{{ Auth::user()->userid }}" id="l_userid">
<input type="hidden" name="l_f_name" value="{{ Auth::user()->f_name }}" id="l_f_name">
<input type="hidden" name="l_l_name" value="{{ Auth::user()->l_name }}" id="l_l_name">
<input type="hidden" name="l_bookid" value="{{$book->bookid}}" id="l_bookid">
<input type="hidden" name="l_title" value="{{$book->title}}" id="l_title">
<input type="hidden" name="ddate" value="" id="ddate">
<input type="submit" name="requaestbtn" value="Confirm">
</form>
<a href="{{url('home')}}" class="btn btn-primary" role="button">
Cancel</a>
</div>
</div>
#endsection
on each loan page there will be the hidden input types that will send the data to the controller but i want the 'ddate' hidden input to have the value of 1 week from now if the user is on the 1 week loan page, 2 weeks from now if they are on the 2 week loan page etc.,
this is the function i have in my controller:
public function loan(Request $request)
{
$loan = new Loan();
$loan->userid = $request->l_userid;
$loan->f_name = $request->l_f_name;
$loan->l_name = $request->l_l_name;
$loan->bookid = $request->l_bookid;
$loan->title = $request->l_title;
$loan->startdate = Carbon::now();
$loan->duedate = $request->ddate
$loan->save();
return view('home');
}

Ok the solution to your question is that you can set the value to a number corresponding to the number of weeks of loan period. In your case the values are 1, 2 and 4. Then in the controller you can generate a date based on the loan period number you've received.
But at the same time i have to warn you about the bad practises you're following. Your form can be edited by the user to loan a book as another person. Never send the user information in the form, it can be edited by the end user. Instead use the currently logged in user's info in the controller directly.
<form action="{{url('loan')}}" method="POST">
{{ csrf_field() }}
<input type="hidden" name="l_bookid" value="{{$book->bookid}}" id="l_bookid">
<input type="hidden" name="l_title" value="{{$book->title}}" id="l_title">
<input type="hidden" name="ddate" value="1" id="ddate">
<input type="submit" name="requaestbtn" value="Confirm">
</form>
public function loan(Request $request)
{
$loanWeeks = min($request->ddate, 4);
$loan = new Loan();
$loan->userid = auth()->user()->userid;
$loan->f_name = auth()->user()->f_name;
$loan->l_name = auth()->user()->l_name;
$loan->bookid = $request->l_bookid;
$loan->title = $request->l_title;
$loan->startdate = Carbon::now();
$loan->duedate = Carbon::now()->addWeeks($loanWeeks);
$loan->save();
return view('home');
}
I've also added a small check to make sure the user can only lease the book for maximum of 4 weeks. If you don't add this check then the end user can again edit the value and loan the books for however long they want.

Can you just put in the view:
<input type="hidden" name="ddate" value="1" id="ddate">
and then in the controller:
$loan->duedate = Carbon::now()->addWeeks($request->ddate);

Related

Thymeleaf form array with default values

I'm using Spring+Thymeleaf to see and modify the users in a database. I would like to set the input fields to the actual values of an original user but I've tried with different styles and it doesn't work.
With the present configuration I can update information of users and see the id of original user (it's not in a input field) but I can't show the actual configuration in input field as default.
CONTROLLER:
#GetMapping(value = {"/", ""})
public String subusersPage(HttpSession session, Model model) {
String idUser = BaseController.getLoggedUser(session);
UserDTO userDTO = userService.getUserById(idUser);
model.addAttribute("subusersDTO", userService.getSubusersDTO(userDTO.getSubusers()));
model.addAttribute("populations", userDTO.getPopulations());
model.addAttribute("configurations", userDTO.getConfigurations());
model.addAttribute("attributes", userDTO.getAttributes());
model.addAttribute("subuserDTO", new SubuserDTO());
return "subusers";
}
HTML:
<th:block th:each="subuserDTO_original : ${subusersDTO}">
<hr>
<form action="#" th:action="#{/subusers/__${subuserDTO_original.id}__}" th:object="${subuserDTO}" method="post">
<div>
<p th:text="${'Id: ' + subuserDTO_original.id}"></p>
<p>Name: <input type="text" th:field="*{name}" th:name="name" th:value="${subuserDTO_original.name}"/></p>
<p>Population: <input type="text" th:field="*{population}" th:name="population" th:value="${subuserDTO_original.population}"/></p>
<p>Configuration: <input type="text" th:field="*{configuration}" th:name="configuration" th:value="${subuserDTO_original.configuration}"/></p>
<p>Attributes: <input type="text" th:field="*{attributes}" th:name="attributes" th:value="${subuserDTO_original.attributes}"/></p>
<p>
<button type="submit" th:name="action" th:value="update">Update</button>
<button type="submit" th:name="action" th:value="delete">Delete</button>
<button type="reset" th:name="action" th:value="clear">Clear</button>
</p>
</div>
</form>
<form action="#" th:action="#{/subusers/__${subuserDTO_original.id}__}" method="get">
<button type="submit">Default</button>
</form>
</th:block>
Any help will be very appreciated, thank you!
If you want to edit an existing user, then your th:object (which is ${subuserDTO} in this case) needs to be populated with the values of the original user. This is because when you use the attribute th:field="*{name}", it actually overwrites the name, id, and value of the html tag (which is why th:value="${subuserDTO_original.name}" isn't working.
Two other options you could do:
You could also set name="name" and use th:value instead.
Or another option, you could use ${subuserDTO_original} as your th:object.

Laravel - CSRF Token Mismatch - Header Token gets regenerated

I'm struggeling the last 2 weeks on the following problem:
First of all my problem only occours when I try to deploy my current Laravel (6.11) project on the live server. On my Localhost everything works fine.
In every FORM I used the #csrf tag to set the token as well as the meta tag in the head section of my page. If I search into the developer tool in Chrome the tokens in head and form match perfectly. When the POST request gets sent I get an 419 Page Expired error. I figured out that the HEAD token gets recreated on each request so a token mismatch occours.
I already tried the following things:
Diffrent syntax of the csrf tag
I excepted all FORMS in the VerifyCsrfToken.php - these ended up in a redirect to my index.php without submited form
I checked all Laravel config settings which were recommended in diffrent Forum Posts
I tried a empty laravel installation with a basic login setup on my server - This worked
I currently work with git. On the a previous commit version (16th of december) which I uploaded to my server on that exact Date I had no problem at all but when I tried to reupload the exact same git commit date, the same problem happens.
Greatings Max
If you need any code I'll upload here.
Controller:
function fakeAuthentifizierung(Request $request){
$username = $request->input('benutzernameLogin');
$password = $request->input('passwortLogin');
session(['key' => 'mt171043']);
session(['eingeloggt' => true]);
/*****
* ABFRAGE ADMINRECHTE
* BITTE DIESEN TEIL SPÄTER IN ECHTE AUTHENTIFIZIERUNG ÜBERNEHMEN
*
*/
$admin = false;
// SPÄTER BENUTZERID AUS LOGIN SESSION ÜBERGEBEN
// astmedin5 als TESTZWECK
$rechte = Benutzer::getBenutzerBerechtigung("astmedin5");
//Berechtigung Abfragen
if($rechte->name != 'Student' && 'Lehrbeauftragter'){
session(['admin' => true]);
}else{
session(['admin' => false]);
}
/***
*
* ABFRAGE ENDE
*/
return redirect(route('index',app()->getlocale()));
}
View:
<form method="POST" action="{{ action('LoginController#FakeAuthentifizierung', app()->getLocale()) }}">
#csrf
<h1>{{ __('Login') }}</h1>
<label class="col" for="benutzernameLogin">{{ __('Benutzername') }}</label>
<input name="benutzernameLogin" id="benutzernameLogin" class="inputLogin col mb-4" type="text"
aria-label="Text input with checkbox" placeholder="{{ __('Benutzername') }}" required>
<label class="col" for="passwortLogin">{{ __('Passwort') }}</label>
<input name="passwortLogin" id="passwortLogin" class="inputLogin col mb-4" type="password"
aria-label="Text input with checkbox" placeholder="{{ __('Passwort') }}" required>
<div class="col-8 float-left">
<input id="checkboxPasswortAnzeigen" type="checkbox">
<label for="checkboxPasswortAnzeigen">{{ __('Passwort anzeigen') }}</label>
</div>
<button type="submit" class="btn-slash col-3 inverted fontLight float-right">{{ __('Login') }}</button>
</form>

i want to send data from one view to another Laravel view

i have two views, view-1 and view-2.
view-1 has form, which will store data temporary.
i want to get data from view-1 and send it to view-2, which has user profile, where temporary data from view-1 will be shown.
how we can achieve it in Laravel, i know we can store data in SQL
and then fetch it, but how to do it without storing to SQL.
my code:
view: 1
<form >
<div class="form-group">
<label class="col-form-label" >Date</label>
<input type="text" name="sdate" class="form-control">
<input type="submit" class="btn btn-primary" value="Add date" >
</div>
</form>
view 2 Controller:
public function report2($id)
{
$teacher = Teacher::teacher($id);
return View('teachers.report2' ,compact('teacher','today','sdate'));
}
Route:
Route::get('teachers/{id}/report2', 'TeachersController#report2');
Use session, for example in view1 you pass variable of date do this on your controller of view 1
session(['sdate' => $request->sdate]);
and then you can get the value of the session in your controller or view by calling this
$date = session('sdate');
further reading see the docs
i was able to do it using simple php;
in view 1 i added this code:
<form action="report2" method="get">
Date: <input type="text" name="today" placeholder="Date of Birth" class="datepicker form-control"><br>
<input type="submit">
</form>
Laravel view 2:
<?php echo $_GET["today"]; ?><br>

Parsing data from blade form to controller using request

I want to parsing my label name="predictDataTemp" in form into my controller, I already set the value form my label, but when I want to request the data still null
content.blade.php
<div class="form-group" align="center">
<label for="exampleResult" name="result">Result</label>
<label for="examplePredict" id="predictData" class="form-control">
<input type="hidden" name="predictDataTemp">
</label>
</div>
controller
public function result(Request $request){
$this->validate($request,[
'mCalories'=>'required',
'mCholesterol'=>'required',
'mFat'=>'required',
'mProtein'=>'required',
'mSugars'=>'required'
]);
$item= array();
array_push($item,array('Calories'=>$request->mCalories,'Cholesterol'=>$request->mCholesterol,'Fat'=>$request->mFat,'Protein'=>$request->mProtein,'Sugars'=>$request->mSugars,'Predict'=>$request->predictDataTemp));
return json_encode($item);
}
Your input has no value.
If you want to give it a value with jQuery (looking at your previous comments)
Give the input an id
<input type="hidden" name="predictDataTemp" id="predictDataTemp">
Then assign it in jQuery
$('#predictDataTemp').val('pass value here');
label don't have name attribute, it has only two attribute for and form so you can pass value in hidden input tag, Read this article
Instead
<label type="text" for="examplePredict" id="predictData" name="predictDataTemp" class="form-control"></label>
Use this
<label type="text" for="examplePredict" class="form-control"></label>
<input type="hidden" name="predictDataTemp" id="predictData" value="something">

Laravel - Upload to Existing Model Record

Maybe it's because I'm tired, but I can't seem to get a simple upload working for one of my models.
On the show details page of my customers (who are NOT users) model, I have a simple form where a user can upload the logo of the customer.
The form:
<form enctype="multipart/form-data" action="/customers/i/{{$customer->url_string}}" method="POST">
<input type="file" name="logoUpload">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<input type="submit" class="pull-right btn btn-sm btn-primary" value="Upload">
</form>
The Controller:
public function logoUpload(Request $request){
if($request->hasFile('logoUpload')){
$path = Storage::putFile('public/customer/uploads', new File(request('logoUpload')));
$customer->car_logo = $path;
$customer->save();
return back();
}
}
I know the issue is that I haven't defined $customer in the controller since the file does actually store itself in the correct folder after I click submit, but it does not hit the database at all.
Update
The current customer details url:
http://localhost:8000/customers/i/dsdado9a98w78721
The web definition for the post route:
Route::post('/customers/i/{customer}', 'CustomerController#logoUpload');
You have to create a hidden field in your form that contains the customer id and then use it in your controller to update it with the new file path, here is an example:
View
<form enctype="multipart/form-data" action="/customers/i/{{$customer->url_string}}" method="POST">
<input type="file" name="logoUpload">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<!-- customer_id field -->
<input type="hidden" name="customer_id" value="{{$customer->id}}">
<input type="submit" class="pull-right btn btn-sm btn-primary" value="Upload">
</form>
Controller
public function logoUpload(Request $request){
if($request->hasFile('logoUpload')){
$path = Storage::putFile('public/customer/uploads', new File(request('logoUpload')));
// get customer
$customer = Customer::find($request->customer_id);
$customer->car_logo = $path;
$customer->save();
return back();
}
}
You have some options, here is a simple one, with only adjusting that controller method:
public function logoUpload(Request $request, $customer)
{
$customer = Customer::where('url_string', $customer)->firstOrFail();
if($request->hasFile('logoUpload')){
$path = Storage::putFile('public/customer/uploads', new File(request('logoUpload')));
$customer->car_logo = $path;
$customer->save();
return back();
}
...
}
We have added a parameter to the method signature to accept the route parameter. We then find the model via url_string matching that parameter.
You also could setup route model binding as well to do the resolving of that model based on the route parameter for you.

Resources