I need some help in my laravel application with passing the values from a form though to another page. I have a table with data on area objects, and I want to be able to select two (or more) area objects, and then view those in a new page.
In my index.blade.php I have the hollowing form:
<form method = "POST" action="/areas/comparison" id="preferencesForm" class="form-group">
!{csrf_field()}!
<table id='areas_table' class="table table-striped">
<thead class="thead-default">
<tr>
<th>Select</th>
<th>Area</th>
<th>Overall Score</th>
<th>Housing Affordability Ratio</th>
<th>Mean House Price</th>
<th>Crime Level</th>
<th>Green Space</th>
<th>Good GCSE's</th>
<th>Number of Pubs & Restaraunts:</th>
<th>Superfast Broadband</th>
</tr>
</thead>
<tbody>
#foreach ($areas as $area)
<tr>
<td scrope="row"><input type="checkbox" name="area[]" value="!{$area->id}!"></td>
<th>!{$area->name}!</th>
<td>!{Helpers::calculateOverallScore($area)}!</td>
<td>!{$area->housing_affordability_ratio}!</td>
<td>£!{$area->mean_house_price_2015}!</td>
<td>!{$area->crime}!</td>
<td>!{$area->greenspace*100}!%</td>
<td>!{$area->five_good_gcses*100}!%</td>
<td>!{$area->restaurants}!/km<sup>2</sup></td>
<td>!{$area->superfast_broadband*100}!%</td>
</tr>
#endforeach
#endif
</tbody>
</table>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" id="compare_button" class="btn btn-primary" value="Compare"/>
</form>
And I would like to then go to show_comparison.blade.php and be able to display the data on the two (or more) areas that I selected.
In routes.php I have:
Route::post('/areas/comparison', 'AreasController#show_comparison');
And then in AreasController:
public function show_comparison(Area $area)
{
$formData = Request::all(); //Get the form data with the facade
return view('areas.show_comparison', compact('formData'));
}
However when I click submit and it tries taking me to show_comparison.blade.php it returns the error message "Trying to get property of non-object".
Here is show_comparison.blade.php:
#extends('layout')
#section('content')
<div class="container">
Back
<h1>Comparison</h1>
<p>Hello, this is the comparison page. !{$formData}!</p>
</div>
#stop
Ideally I would like to be able to print the data in the form of !{ area1->name}! and !{area2->name}! according to my selection.
If anyone can show my how I should be passing form selected data through to another page that would be amazing. (Thank you for taking the time to read this.)
I was given an answer on another forum. This solution will take the id that the form passes it, then will fetch the corresponding area objects and pass these in an array to the show_comparisons.blade.php view.
public function show_comparison(Request $request)
{
$areas= Area::whereIn('id',$request->area)->get();
return view('areas.show_comparison', compact('areas'));
}
Related
I am a beginner in the Laravel framework, and I am having some trouble trying to store the data that was inserted in a form into a Collection.
This is the form where you get the data
<form action="{{ url('/add_client') }}" method="POST">
#csrf
<table>
<tr>
<td><input type="text" placeholder="Add Client" name="client" required></td>
<td><input type="submit" value="+"></td>
</tr>
</table>
</form>
This is where the data is outputed
<table>
<tr><td>Added Clients</td></tr>
<tr><td>
<div class="border border-dark" style="width: 500px; height: 100px;">
#isset($clients)
#foreach ($clients as $client)
<div class="bg-info" style="display: inline-block; padding: 2px;">{{ $client }}</div>
#endforeach
#endisset
</div>
</td></tr>
</table>
This is where a new collection is added, inserting the data that was read from the form, and go back to the view '/client' which is the page where the data gets read and will be outputed
public function addClient (Request $req, Collection $clients) {
$clients->push($req->input('client'));
return view('client')->with('clients', $clients);
}
This is the routing page (The fetchData function is unrelated)
Route::get('/client', [ClientController::class, 'fetchData']);
Route::post('/add_client', [ClientController::class, 'addClient']);
I would like that the $clients variable created a new "entry" for each time that data was submitted, and I would like to be able to continue to access the data that was submitted before and inserted into the collection. I don't want to store it into a database.
I am new to Vue js, I have tried to find answers for my problem everywhere but in vain.
I just try to send an array (shopping cart) to Laravel from Vue component, but I only get [object Object] when I try to use foreach loop to get the items in the array. What do I do wrong?
I should be able to get name of title, quantity and price etc., this all works in my website in Vue component, but when I try to send to Laravel it is impossible to read it.
This is some of my code, please advice me.
<form action="../api/checkout" method="post" #submit="checkout">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Artiklar</th>
<th scope="col">Antal</th>
<th scope="col">Pris</th>
<th scope="col">Summa</th>
<th scope="col">Radera</th>
</tr>
</thead>
<tbody>
<input type="hidden" name="cartobj" v-bind="cartitem">
<tr v-for="(crt, index) in cart" :key="index">
<td>{{ crt.title }}<br><img :src="/image/+crt.image" :alt="crt.image" style="height: 80px;"></td>
<td>{{ crt.qty }} st <br><div class="row">
<button class="btn btn-link col-md-6" #click="decrease(index)">-</button>
<button class="btn btn-link col-md-6" #click="increase(index)">+</button>
</div></td>
<td>{{ crt.subprice }} kr</td>
<td>{{ (crt.subprice*crt.qty).toFixed(2) }} kr</td>
<td><button #click="removecart(index)" class="btn btn-link"><img src="/pic/trash.png" alt="" width="20"></button></td>
</tr>
</tbody>
</table>
<p class="border rounded text-right p-2"><b>Total: {{ subsum }} kr</b></p>
<button id="checkout" class="btn btn-success col">Gå till kassan</button>
</form>
export default {
props: ['product'],
data() {
return {
cartitem: {
title: this.product.article,
qty: 1,
subprice: (this.product.price/100).toFixed(2),
image: this.product.image
},
cart: []
}
},checkout() {
let c = {cartobj: this.cart};
axios.post('../api/checkout', JSON.stringify(c));
}
From my controller, I have tried many different things, but can not get it to work, even nestled foreach loops...
public function checkout(Request $request)
{
$cart = request();
foreach($cart as $d=>$c) {
echo $d;
}
die();
}
Change your controller code to this and see if that helps:
public function checkout(Request $request)
{
$cart = $request->all();
foreach($cart as $d=>$c) {
echo $d;
}
die();
}
You can also access specific input values, like this:
$name = $request->input('name');
The HTML form contains inputs with object values:
<input type="hidden" name="cartobj" v-bind="cartitem">
Submitting a native form with an input like this will result in [object Object] being sent in the request.
And, although configured to call the checkout function upon submit, the form is also configured to POST to ../api/checkout without the use of JavaScript:
<form action="../api/checkout" method="post" #submit="checkout">
What is likely happening here:
User submits form
checkout() is called
In parallel, the native form is submitted. The native form takes priority
You can prevent the native form from submitting itself by using #submit.prevent="checkout", like this:
<form #submit.prevent="checkout">
Adding .prevent to a Vue event handler stops the native handlers from firing. In this case, .prevent stops the HTML form from being submitted without the use of the checkout function.
For more information on Vue's .prevent, see the Vue Event Modifier docs.
For more information on preventing the native handling of events, see Event.preventDefault() on MSDN.
im new to laravel. So im trying to delete a record from database from my index page. But it only delete the record with the lowest primary key value, my id field.
Here's my controller code for destroy function:
public function destroy(Province $province)
{
//
$findProvince = DB::table('provinces')->where('id', $province->id)->delete();
if($findProvince){
return redirect()->route('provinces.index')->with('success', 'Province deleted successfully');
}
return back()->with('error', 'Province could not be deleted');
//var_dump($province->id);
}
Here's my view code:
#extends('layouts.app')
#section('content')
<div class="col-md-8 offset-md-2">
<br/>
<div>
Add New Province
</div>
<br/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Image</th>
<th scope="col">Operations</th>
</tr>
</thead>
<tbody>
#foreach($provinces as $province)
<tr>
<th scope="row">{{ $province->id }}</th>
<td>{{ $province->name }}</td>
<td><img src="../{{ $province->imgPath }}" width="200px"/></td>
<td>
Edit |
<a
class="btn btn-danger"
href="#"
onclick="
var result = confirm('Are you sure you wish to delete this province?');
if( result ){
event.preventDefault();
document.getElementById('delete-form').submit();
}
">Delete
</a>
<form id="delete-form" action="{{route('provinces.destroy', $province->id)}}" method="POST" style="display: none;">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
I tried using var_dump on the $province->id but it only output the lowest 'id' value.
id's are unique. You will get this unexpected behavior if you use the same id in a loop. Either use unique id's or put your buttons inside the form (I suggest this).
<td>
<form class="delete-form" action="{{ route('provinces.destroy', $province->id) }}" method="POST">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
Edit |
<a class="btn btn-danger">Delete</a>
</form>
</td>
And then use this Javascript in a seperate file for confirmation:
(function(){
let forms = document.querySelectorAll('form.delete-form');
[].forEach.call(forms, function(form){
form.onsubmit = function(e) {
if ( ! confirm('Are you sure you wish to delete this province?'))
return e.preventDefault();
}
});
})();
If you still want to use your approach, add the id of $province to the id attribute of your form. This will make your form unique so you get access it with an id.
<form id="delete-form-{{ $province->id }}" ...>
And then your Javascript:
if( result ){
event.preventDefault();
document.getElementById('delete-form-{{ $province->id }}').submit();
}
Thanks everyone for your help. And sorry that it took me long to reply. I've been really busy with other schools. So i managed to track down the problem with my code. It's with my view. All the created delete form has the same id. So if i just added the record id to the form. It works just fine.
I`m developing attendance management system.
My view is like this.
What I need is if I select the time value and press Mark here button current data and time value need to be stored in the database according to trainee ID.
Here is the view for that .
<table class="table table-striped">
<thead>
<th>Trainee ID</th>
<th>Name with Initials</th>
<th>Time</th>
<th>Mark Here!</th>
</thead>
<tbody>
#foreach($items as $item)
<tr>
<td>
<div class="form-group">
<input type="text" name="trainee_id" class="form-control" value="{{ $item->trainee_id }}">
</div>
</td>
<td>
{{ $item->name_with_initials }}
</td>
<td>
<label><input type="checkbox" name="time" id="time" value="time"> Time</label>
</td>
<td>
<a class="btn btn-info" href="Bankdetails/{{ $item->trainee_id }}">Mark Here</a>
</td>
</tr>
#endforeach
</tbody>
</table>
I know that my Controller is perfectly alright and need to be fixed.
public function store(Request $request)
{
$queryType = $request->time;
$carbon = new Carbon('queryType');
attendancedetails::create($request->all());
return view('traineeattendance.attendanceo');
}
Here is the necessary data model .
class attendancedetails extends Model
{
protected $table = "attendancedetails";
protected $fillable = ['id',
'attendance_date',
'trainee_id',
'name',
'starting_time',
'end_time',
'site_visit_time'];
}
Can anyone suggest me to get fixed this.
You already have the current time by default in laravel. When you save a record in migrations there is a timestamps(); input:
public function up()
{
Schema::create('users', function (Blueprint $table) {
...
$table->timestamps();
});
}
That creates a created_at and updated_at column in your DB table! And you can use created_at time when that input is saved to show it elsewhere!
i have code with laravel 5.4
i wanna show data from database with filter date...
how it's work? can help me?
view.blade.php
database
and this's my code in view.blade.php
<div class="table-responsive">
<table class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th><strong>No</strong></th>
<th><strong>Nama</strong></th>
<th><strong>Alamat</strong></th>
<th><strong>Lokasi</strong></th>
<th><strong>Tanaman</strong></th>
<th><strong>Jumlah Panen</strong></th>
<th><strong>Luas Lahan</strong></th>
</tr>
</thead>
<tbody>
#foreach($hasil as $key => $data)
<tr>
<th>{{$no++}}</th>
<th>{{$data->nama_user}}</th>
<th>{{$data->alamat}}</th>
<th>{{$data->id_lokasi}}</th>
<th>{{$data->nama_tanaman}}</th>
<th>{{$data->jumlah_panen}}</th>
<th>{{$data->luas_lahan_panen}} HA</th>
</tr>
#endforeach
</tbody>
</table>
</div>
<div class="col-sm-3">
<div class="box">
<div class="box-header with-border">
<h3 class="box-title">Filter</h3>
<p>Pilih Tanggal : {!! Form::input('month', 'published_at', null, ['class' => 'form-control']) !!}</p>
<button name="filter" class="btn btn-primary form-control" id="filter" onclick="filter">Pilih Tanggal</button>
</div>
</div>
</div>
and this's the code from web.php (route)
Route::get('laporhasil', function () {
$hasil = DB::select("SELECT `tbl_user`.`nama_user`, `tbl_user`.`alamat`, `tbl_lapor_hasil`.`id_lokasi`, `tbl_tanaman`.`nama_tanaman`, `tbl_lapor_hasil`.`luas_lahan_panen`,`tbl_lapor_hasil`.`jumlah_panen`FROM `tbl_lapor_hasil` INNER JOIN `tbl_user` ON `tbl_lapor_hasil`.`id_user` = `tbl_user`.`id_user` INNER JOIN `tbl_tanaman` ON `tbl_lapor_hasil`.`id_tanaman` = `tbl_tanaman`.`id_tanaman`");
$no = 1;
return view('laporhasil', ['hasil' => $hasil], ['no' => $no]);
});
If you want to get all data which are created today then you then you can follow this code snippet-
$data = Modelname::whereDate('created_at','=',\Carbon\Carbon::now())->get();
//Assuming you have a date field named `created_at`
If you want to get data by specific day then -
$data = Modelname::whereDay('created_at','=',$day)->get();
Same way you can get data by month or year.
$data = Modelname::whereMonth('created_at','=',$month)->get();
$data = Modelname::whereYear('created_at','=',$year)->get();
The $day, $month, $year represents day, month and year value respectively.
Make a filter form with get method and same route in the action as the route view.blade.php.
i.e. if your route of view.blade.php is my-data then make a filter form like
<form action="{{route('my-data')}}" method="GET">
<input type="text" name="date" class="some-class" />
<input type="submit" value="Filter" />
</form>
And the method of the route my-data like -
public function myData(Request $request){
$model = new Mymodel(); // This is you model name of the corresponding table
if(!empty($request->date)){
$model = $model->whereDate('date','=', $request->date);
}
if(empty($request->date)){
$result = Mymodel::all();
}else{
$result = $model->get();
}
return view('view', compact('result'));
}
This method checks if the request has date field and it's value or not. If it finds date field then fetch the data from Mymodel. Careful about not to use ->get(). Finally check if the request has no date field then request all the data you want to fetch from Mymodel otherwise get the filtered data to your view.