How to incremented in table on button click laravel - php

I have Home.blade.php in which if I click vote button it should increment the count in candidate table.
home.blade.php
#foreach ($file as $show)
<div class="col-md-3" style="margin-bottom: 20px;">
<div class="card">
<img src="{{$show->image}}" style="width:100%">
<div class="card-body">
<h5 class="title">President</h5>
<p class="card-text">Name : {{$show->name}}</p>
<button>VOTE</button>
</div>
</div>
</div>
#endforeach
homecontroller
public function Count(){
DB::table('candidate')->increment('count');
return view('/home')->with('success', 'voted');
}
Route
Route::get('/home','Homecontroller#Count');
Please help me to increment the count, if not this method is there any other method to do the same.

Yes, there is a better way.
Add this to Your web.php
Route::put('/votesUp/{vote}', 'HomeController#upVote')->name('votes.upVote');
Route::put('/votesDown/{vote}', 'HomeController#downVote')->name('votes.downVote');
in your view list thats is index.blade.php add this two buttons
FORM BUILDER WAY
#foreach($candidates as $item)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{!! $item->name !!}</td>
<td>{!! Form::model($item, ['method' => 'PUT', 'route' => ['votes.upVote', $item->id ] ,'enctype'=>'multipart/form-data' ]) !!}
{!! Form::submit( 'Up Vote', ['class' => '', 'name' => 'submitbutton', 'value' => 'upvote'])!!}
{!! Form::close() !!}</td>
<td>{!! Form::model($item, ['method' => 'PUT', 'route' => ['votes.downVote', $item->id ] ,'enctype'=>'multipart/form-data' ]) !!}
{!! Form::submit( 'Down Vote', ['class' => '', 'name' => 'submitbutton', 'value' => 'upvote'])!!}
{!! Form::close() !!}</td>
</tr>
#endforeach
HTML WAY
#foreach($candidates as $item)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{!! $item->name !!}</td>
<td>
<form method="post" action="{{ route('votes.upVote', $item->id) }}">
#method('PUT')
#csrf
<input class="" name="submitbutton" value="Up Vote" type="submit">
</form>
<form method="post" action="{{ route('votes.downVote', $item->id) }}">
#method('PUT')
#csrf
<input class="" name="submitbutton" value="Down Vote" type="submit">
</form>
</td>
</tr>
#endforeach
I am Considering Your model as Candidate so add this to HomeController
ELOQUENT way
public function upVote(Request $request, $id)
{
Candidate::find($id)->increment('votes_count', 1);
return redirect()->back();
}
public function downVote(Request $request, $id)
{
Candidate::find($id)->decrement('votes_count', 1);
return redirect()->back();
}
DB Facade Way
public function upVote(Request $request, $id)
{
\DB::table('candidates')->where('id','=',1)->increment('votes_count', 1);
return redirect()->back();
}
public function downVote(Request $request, $id)
{
\DB::table('candidates')->where('id','=',1)->decrement('votes_count', 1);
return redirect()->back();
}
Explained:
When You click on the upvote button filed votes_count in candidates table will be
incremented by 1
When You click on the downvote button filed votes_count in candidates table will be decremented by 1
EDIT FOR undefined variable candidate
Find this line
#foreach($candidates as $item)
And Replace with
#foreach ($file as $item)
FIX FOR
Class App\Http\Controllers\HomeController does not exist
From
Route::put('/votesUp/{vote}', 'HomeController#upVote')->name('votes.upVote');
Route::put('/votesDown/{vote}', 'HomeController#downVote')->name('votes.downVote');
TO
Route::put('/votesUp/{vote}', 'Homecontroller#upVote')->name('votes.upVote');
Route::put('/votesDown/{vote}', 'Homecontroller#downVote')->name('votes.downVote');
Your Controller Class
Homecontroller
but i have wrongly written as
HomeController

Make sure your column count is integer type in migration
And:
You are writing it in wrong way
<button>VOTE</button>
change it to
<button>VOTE</button>

The vote button should be like this:
<button>VOTE</button>

With the functionalities like Upvote and Downvote as answered nicely by #manojkiran-a above, I would also add throttling. Now a days it is easy to create a bot which will send upvote requests even when you are using csrf token.
I would add :
'middleware' => 'throttle:5'
Which will allow only 5 requests per minute per IP address. Not entirely preventing it but making it little harder.
Route::put('/votesUp/{vote}', 'Homecontroller#upVote')->middleware('throttle:5')->name('votes.upVote');
Route::put('/votesDown/{vote}', 'Homecontroller#downVote')->middleware('throttle:5')->name('votes.downVote');

Related

undefined index on empty array laravel 5

Fellow coders,
It might be a stupid question but I really am stuck on this part in my application.
I am making an hourregistration system for the company i'm an intern at. What I have done is creating a delete button in my application that deletes a record with the click of a simple button. Yet what I did was to delete all the visible records in the table I created that shows all the registrations.
When I deleted the final record I got an error of "undefined index hourregistration".
public function index()
{
$hoursregistrations = Hoursregistration::latest()->get();
$user_id = Sentinel::getUser();
$project_id = Project::pluck('description', 'id');
$company_name = Company::where('status','client')->pluck('company_name', 'id');
$activity_name = Subproject::pluck('id');
//dd($hoursregistrations);
return view('hoursregistrations.index', compact('hoursregistrations', 'user_id', 'project_id',
'activity_name', 'company_name'));
}
I think the problem lies at
$hoursregistrations = Hoursregistration::latest()->get();
Because I'm trying to get the latest value of the registration but there is none right?
Now i'm wondering how I could still show my view without breaking my inserting and/or viewing portion of the app.
#foreach ($hoursregistrations as $hoursregistration)
<tr>
<td hidden>{{ $user_id->first_name }}</td>
<td >{!! App\Project::getCompanyName($hoursregistration->project_id) !!} - {!! \App\Subproject::getTaskTitle($hoursregistration->subproject_id)!!}</td>
<td>{!! $hoursregistration->note !!}</td>
<td>{!! \App\Helpers::dateFormat($hoursregistration->date) !!}</td>
<td>{!! $hoursregistration->hours !!}</td>
<td>
<button id="btn-edit" name="btn-edit" class="btn btn-warning btn-xs btn-detail open-modal" value="{{$hoursregistration->id}}">Edit</button>
<form action="hoursregistrations/{{ $hoursregistration->id }}/delete" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button id="btn-delete" type="submit" name="btn-delete" class="btn btn-danger btn-xs btn-delete delete-hoursregistration" value="{{ $hoursregistration->id }}">Delete</button>
</form>
</td>
</tr>
#endforeach
This is the foreach loop that shows the data in the index.blade.php view
I would love some help so I can continue finishing this application
public function index()
{
$hoursregistrations = Hoursregistration::latest()->get();
$user_id = Sentinel::getUser();
$project_id = Project::pluck('description', 'id');
$company_name = Company::where('status','client')->pluck('company_name', 'id');
$activity_name = Subproject::pluck('id');
//dd($hoursregistrations);
return view('hoursregistrations.index', compact('hoursregistrations', 'user_id', 'project_id',
'activity_name', 'company_name'));
}
Everything is about s or not s.
The error you are talking about is because you have an occurrence of $hoursregistration (without s) before or after the #foreach of your view. The solution is to check and remove occurrence of $hoursregistration outside your loop:
// You can't use $hoursregistration before
#foreach ($hoursregistrations as $hoursregistration)
{{-- ... do what you want with $hoursregistration --}}
#endforeach
// You can't use $hoursregistration after
I am sure there is a confusion (typo) between $hoursregistration, $hoursregistrations and $hourregistration (the confusion is even in your post VS comment)
you can use if here if $hoursregistrations exists then it populate data else nothing happen
#if($hoursregistrations)
#foreach ($hoursregistrations as $hoursregistration)
<tr>
<td hidden>{{ $user_id->first_name }}</td>
<td >{!! App\Project::getCompanyName($hoursregistration->project_id) !!} - {!! \App\Subproject::getTaskTitle($hoursregistration->subproject_id)!!}</td>
<td>{!! $hoursregistration->note !!}</td>
<td>{!! \App\Helpers::dateFormat($hoursregistration->date) !!}</td>
<td>{!! $hoursregistration->hours !!}</td>
<td>
<button id="btn-edit" name="btn-edit" class="btn btn-warning btn-xs btn-detail open-modal" value="{{$hoursregistration->id}}">Edit</button>
<form action="hoursregistrations/{{ $hoursregistration->id }}/delete" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button id="btn-delete" type="submit" name="btn-delete" class="btn btn-danger btn-xs btn-delete delete-hoursregistration" value="{{ $hoursregistration->id }}">Delete</button>
</form>
</td>
</tr>
#endforeach
#endif
i think this might help

Updating multiple records using Laravel 5.3 model binding

I am pulling multiple records from MySQL and looping through model binding and filling all the input fields with some data.
Now, I may change 2 or 10 or all 26 fields and hit update button. I want to update all the records. Now, I don't know how $id works here? usually I update single record and I have $id which I can find and update only that field.
But that's not the case here. I am pulling 13 records(or 26 fields). 13 field_1 and 13 field_2. How to update all?
mycode
Database
Table
-id
-name
-field1 (updating this one)
-field2 (updating this one)
Routes
Route::get('/cat' , 'AdminController#cat');
Route::patch('/cat/{$id}/update','AdminController#cat_update');
Controller
public function cat(){
$cattfs = Catf::all();
return view('/cat',compact('cattfs'));
}
public function cat_update(Request $request, $id) // id = 1
{
$rules = array(
'field1' => 'required',
'field2' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return Redirect()->back()->withErrors($validator);
} else {
$cat = Cattf::find($id); //This wont work :/
$cat ->field1 = Input::get('field1');
$cat ->field2 = Input::get('field2');
$cat ->save();
return redirect('/cat');
}
}
Views
<div class="col-md-6" style="background-color:#fff">
<table class="table table-hover">
<thead>
<tr>
<th style="text-align: center">Product</th>
<th style="text-align: center">Pr</th>
<th style="text-align: center">Co</th>
</tr>
</thead>
<tbody>
#foreach ($cattos as $catto)
{!! Form::model($catto,[ 'method' =>'PATCH', 'url' => ['/cat/.$catto->id./update']]) !!}
<tr>
<td>{{$catto->name}}</td>
<td> {!! Form::text('field1' ,null , ['class'=>'form-control']) !!}</td>
<td> {!! Form::text('field2' ,null , ['class'=>'form-control']) !!}</td>
</tr>
#endforeach
<td colspan="3">
{!! Form::submit('UPDATE', ['class'=>'btn btn-primary btn-block']) !!}
{!! Form::close() !!}
</td>
</tr>
</tbody>
</table>
</div>
snapshot of the form
I don't think you can do this with Model binding (correct me if I'm wrong someone).
What you can instead do is generate an array of data to post to your controller.
For example:
{!! Form::open(['route' => 'catupdate']) !!}
#foreach ($cattos as $catto)
<tr>
<td>{{$catto->name}}</td>
<td>{!! Form::text('categories['.$catto->id.'][field1]', null, ['class'=>'form-control']) !!}</td>
<td>{!! Form::text('categories['.$catto->id.'][field2]', null, ['class'=>'form-control']) !!}</td>
</tr>
#endforeach
{!! Form::close() !!}
You should then receive an array in your controller, which you can loop around and update each record.
public function catupdate()
{
$categories = request()->input('categories');
foreach($categories as $id => $values) {
$cat = Cattf::find($id);
$cat->field1 = $values['field1'];
$cat->field2 = $values['field2'];
$cat->save();
}
}
You can then also validate the array by doing the following in your Request file
public function rules()
{
return [
'categories.*.field1' => 'required',
'categories.*.field2' => 'required'
];
}
this is untested and is an example demonstrating the concept

Laravel 5.4 change user role

I trying make changing role in my panel admin. But when i made it my form dont sending post request. Now only working showing user role. I cant fix it becouse when i click button to switch i dont get any error and role is not changing.
I use HttpRequester when i use url /admin/change its showing this error:
MethodNotAllowedHttpException in RouteCollection.php line 233
There is my code:
View:
#extends('layouts.app')
#section('content')
<h2>Panel Admina</h2>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Imię</th>
<th>Nazwisko </th>
<th>E-mail </th>
<th>Nr.tele </th>
<th>Użytkownik </th>
<th>Moderator </th>
<th>Admin </th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<form action="{{route('change')}}" method="post">
{{ csrf_field() }}
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->lastname }}</td>
<td>{{ $user->email }}<input type="hidden" name="email" value="{{ $user->email }}"></td>
<td>{{ $user->phonenumber }}</td>
<td><input type="checkbox" {{ $user->hasRole('User') ? 'checked' : '' }} name="role_user"/></td>
<td><input type="checkbox" {{ $user->hasRole('Moderator') ? 'checked' : '' }} name="role_moderator"/></td>
<td><input type="checkbox" {{ $user->hasRole('Admin') ? 'checked' : '' }} name="role_admin"/></td>
<td><input type="submit" class="btn btn-default btn-sm" value="Przydziel rolę"></td>
</form>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endsection
Controller:
public function change(Request $request)
{
$user = User::where('email', $request['email'])->first();
$user->roles()->detach();
if ($request['role_user']) {
$user->roles()->attach(Role::where('name', 'User')->first());
}
if ($request['role_moderator']) {
$user->roles()->attach(Role::where('name', 'Moderator')->first());
}
if ($request['role_admin']) {
$user->roles()->attach(Role::where('name', 'Admin')->first());
}
return redirect()->back();
}
Routing:
Route::get('/admin', [
'uses' => 'AdminController#index',
'middleware' => 'roles',
'roles' => ['Admin']
]);
Route::post('/admin/change', [
'uses' => 'AdminController#change',
'as' => 'change',
'middleware' => 'roles',
'roles' => ['Admin']
]);
I really dont know how i can resolve my problem.
try to pass the user id to your route and your form action and instead of post make it put for example:
<form action="{{route('change', $user->id)}}" method="post">
and in your route:
Route::put('/admin/change/{id}', [
'uses' => 'AdminController#change',
'as' => 'change',
'middleware' => 'roles',
'roles' => ['Admin']
]);
and in your controller:
public function change(Request $request, $id)

Laravel Form Model binding with dynamic table rows and auto fill from db

Laravel 5.2
My create form has the ability to dynamically add tr rows via jquery to insert more data into db. How do I pull this data and auto fill my edit form using Form Model Binding (or another way).
UPDATE due to Nazmul Hasan comment:
Code Examples:
View: (Supplier hasmany relationship with supplier extras)
#foreach ($supplier['SupplierExtra'] as $extra)
<tr class="master">
<td>{!! Form::text('SupplierExtraName[]', $extra->name, ['class' => 'form-control']) !!}</td>
<td>{!! Form::text('SupplierExtraCost[]', $extra->cost, ['class' => 'form-control']) !!}</td>
Controller:(store)
foreach ($request->get('SupplierExtraName') as $i => $row) {
if ($request->SupplierExtraName[$i] != null) {
Extra::create([
'supplier_id' => $supplier->id,
'name' => $request->SupplierExtraName[$i],
'cost' => $request->SupplierExtraCost[$i],
]);
}
}
Controller: (update) - UNKNOWN code
How do I tell Laravel which row to update in the db?
So following from Nazmul Hasan comment I have the following store function in my controller
Update Controller:
foreach ($request->get('SupplierExtraName') as $key => $row) {
Extra::where('id', $key)->update([
'name' => $request->SupplierExtraName[$key],
'cost' => $request->SupplierExtraCost[$key],
]);
Updated view:
#foreach ($supplier['SupplierExtra'] as $extra)
<tr class="master">
<td>{!! Form::text("SupplierExtraName[$extra->id]", $extra->name, ['class' => 'form-control']) !!}</td>
<td>{!! Form::text("SupplierExtraCost[$extra->id]", $extra->cost, ['class' => 'form-control']) !!}</td>
<td></td>
<td>
<button type="button" class="btn btn-primary btn-md addRow">
<span class="glyphicon glyphicon-plus-sign"></span> Add a row
</button>
</td>
</tr>
#endforeach
From what I can understand with your questions, you can try these:
1 Considering you have create the Model firsthand, get all that Model.
If you have not created the model, you can try:
php artisan make:model Example
For the sake of example, let's call it Example model.
Here might be its data:
----------------------------------------
ID Name Age Phone
----------------------------------------
1 Sam 20 12345
2 Mia 23 11234
2 Pull out all the data from the controller first
public function functionName(Example $example){
//We try to filter based on what your id is, say, id = 1
//then we store that inside a variable
$example = App\Example::where('id', '=', $example->id)->get();
//Passing the data using compact
return view('yourview', compact('example'));
}
3 Filling the form with your data
You need to put your data in this step, using foreach loop and putting the value using 'value' attribute inside html tag.
<form>
#foreach($example as $e)
<div class="input-group">
<h2 class="input-group">Category's Name</h2>
<!-- the $e->Name is from the data we passed previously -->
<input type="text" class="form-control input-lg" name="Name" value="{{ $e->Name }}">
</div>
#endforeach
</form>
Guess what will fill the text-input? That will be Sam.
The 'value' attribute inside the text-input is what you're looking far, as far as I understand.

Pass $id from blade to controller method show Laravel 4

I am a laravel beginner and trying to pass id to controller method show. It does not showing anything after page reloads. I tried some google stuffs. It didnt bring any help. My related code is given below :
admin.blade.php
<div class="showOne">
<?php if(isset($users)){
var_dump($users);
}
?>
#foreach($inputs as $key => $user)
<tr>
<td>{{ ++$key }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->address }}</td>
<td>{{ $user->phone }}</td>
<td>
{{ Form::open(['route' => ['admin.show', $user->id], 'method' => 'get']) }}
{{ Form::button('Details') }}
{{ Form::close() }}
</td>
<td>
{{ Form::open(['route' => ['admin.edit', $user->id], 'method' => 'get']) }}
{{ Form::button('Edit') }}
{{ Form::close() }}
</td>
<td>
{{ Form::open(['route' => ['admin.delete', $user->id], 'method' => 'get']) }}
{{ Form::button('Delete') }}
{{ Form::close() }}
</td>
</tr>
#endforeach
controller:
class AdminController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
// get all the inputs
$inputs = Userdatas::all();
// load the view and pass the inputs
return View::make('pages.admin')
->with('inputs', $inputs);
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$user = Userdatas::find($id);
var_dump($user);
die();
return View::make('pages.admin')
->with('users', $user);
}
}
routes:
Route::get('admin', [
'uses' => 'AdminController#index'
]);
Route::get('admin/{id}', [
'uses' => 'AdminController#show',
'as' => 'admin.show'
]);
You could just use a link and let Laravel handle it to the propper action via your routes.
See the example below:
// Management
Route::get('management', 'ManagementController#showUser');
Route::get('management/add', 'ManagementController#showAdd');
Route::post('management/add', 'ManagementController#postAdd');
Route::get('management/edit/{id}', 'ManagementController#showEdit');
Route::post('management/edit/{id}', 'ManagementController#postEdit');
Route::get('management/delete/{id}', 'ManagementController#showDelete');
Route::post('management/delete/{id}', 'ManagementController#postDelete');
You can then just make links in your tables and style them via css as buttons.
#foreach($ManagementAll as $Management)
<tr>
<td>{{$Management->username}}</td>
<td>{{$Management->firstname}}</td>
<td>{{$Management->lastname}}</td>
<td>{{$Management->email}}</td>
<td>{{$Management->created_at}}</td>
<td>{{$Management->updated_at}}</td>
<td style="padding-top: 3px; padding-bottom: 0px;">
<a class="btn btn-default btn-circle" href="{{ URL::to('management/edit/' . $Management->id) }}"><i class="fa fa-pencil"></i></a>
<a class="btn btn-default btn-circle" href="{{ URL::to('management/delete/' . $Management->id) }}"><i class="fa fa-times"></i></a>
</td>
</tr>
#endforeach
Controller Show:
public function showEdit($ID)
{
//Return View With Management User Information
return View::make('management.edit')
->with('User', Management::find($ID));
}
Controller Post:
public function postEdit($ID)
{
//Handle Input
//Validation?
//Update Record
//Redirect Back
}
See this website for more information about this topic:
https://scotch.io/tutorials/simple-laravel-crud-with-resource-controllers
Update
My view folder looks like this:
views
management
overview.blade.php
add.blade.php
edit.blade.php
delete.blade.php

Categories