Laravel 5.4 change user role - php

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)

Related

How to call controller's update function

I am trying to use controller's update function on my dashboard.blade.php page, but when I press on "Save" it switches to show.blade.php page instead of updating.
My dashboard.blade.php page:
#if(count($posts) > 0 )
<table class="table table-striped">
<tr>
<th>Title</th>
<th>Body</th>
<th>Employee Number</th>
<th>Edit</th>
<th>Save</th>
</tr>
#foreach($posts as $post)
<tr>
<td>{{$post->title}}</td>
<td><input type='text' name='body'class='form-control' value='{{$post->body}}'></td>
<td>{{$post->employee_no}}</td>
<td><a href="{{ action("PostsController#update", $post->id) }}" >Save</a></td>
<td>Edit</td>
</tr>
#endforeach
</table>
#else
<p>You Have No Posts</p>
#endif
My update function on PostsController.php page:
public function update(Request $request, $id)
{
$this->validate($request,[
//'title' => 'required',
'body' => 'required'
]);
//Update Post
$post = Post::find($id);
//$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('/posts')->with('success','Post Updated');
}
I read that "action" will go to the first route that matches the pattern, but I do not know how to solve this problem.
My web.php page:
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::get('/services', 'PagesController#services');
Route::resource('posts','PostsController');
Auth::routes();
Route::get('/dashboard', 'DashboardController#index');
How can I call the update function correctly from dashboard.blade.php page?
To update data you have to use form with put method.
and route will be like this,
Route::put('dashboard/update/{id}',[
'uses' => 'DashboardController#update',
'as' => 'dashboard.update'
]);
For more Laravel Routing
Hope it helps :)
You can solve this by using form submit with hidden PUT method.
<form action="{{ url('customers') }}/{{$data['customer']->id}}" method="POST">
<input type="hidden" name="_method" value="PUT">
#csrf
</form>
How about having a simple form for each row in the table :
#if(count($posts) > 0 )
<table class="table table-striped">
<tr>
<th>Title</th>
<th>Body</th>
<th>Employee Number</th>
<th>Edit</th>
<th>Save</th>
</tr>
#foreach($posts as $post)
<tr>
<td>{{$post->title}}</td>
<td>{{$post->employee_no}}</td>
<td>
<!-- Form for each row -->
<form action="{{ route("posts.update", [ 'post' => $post->id ]) }}" method="POST">
#method('PUT')
#csrf
<input type='text' name='body'class='form-control' value='{{$post->body}}'></td>
<button type="submit">Save</button>
</form>
<!-- Form for each row -->
<td>Edit</td>
</tr>
#endforeach
</table>
#else
<p>You Have No Posts</p>
#endif

How to incremented in table on button click laravel

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');

Adding Data to the multiple column in laravel 5.7

Hi I am working on a project and I need to do some addition while working on a table.
like I have to fill the three fields and change the status to 2 using checkbox Array. I tried it all but with no luck. Kindly look into it and Let me know the changes I can Do.
My Model CustomerLoad.php is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CustomerLoad extends Model
{
protected $fillable = [
'driver_id',
'vehicle_id',
'company_id',
'customer_id',
'package_type',
'from',
'to',
'in_mile',
'weight',
'height',
'width',
'length',
'rate',
'duration_text',
'ticket_number',
'status_id'
];
public function status()
{
return $this->belongsTo('App\Status');
}
}
My Controller for creating the page is Like this
public function create()
{
$csloads = CustomerLoad::paginate(4);
$driver = Driver::pluck('name', 'id')->all();
$vehicle = Vehicle::pluck('vin', 'id')->all();
$company = Company::pluck('name', 'id')->all();
return view('customerload.create', compact('csloads', 'driver', 'vehicle', 'company'));
}
for storing it
public function updatecsloads(Request $request)
{
if(isset($request->update_all) && !empty($request->checkBoxArray)){
$csloads = CustomerLoad::findOrFail($request->checkBoxArray);
foreach($csloads as $csload){
$input = $request->all();
dd($input);
// $csload->update($input);
}
// return redirect()->back();
// } else {
// return redirect()->back();
}
}
My View is like
<div class="card">
<div class="card-header card-header-rose card-header-text">
<div class="card-ttle">
<h4 class="card-text">Allocate Loads</h4>
</div>
</div>
<div class="card-body">
{!! Form::model(['method' => 'PATCH', 'action' => ['CustomerLoadsController#updatecsloads']]) !!}
<div class='form-group'>
{!! Form::select('checkBoxArray', ['' => 'Allocate'], null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>''])!!}
</div>
<div class='form-group'>
{!! Form::submit('Allocate Loads', ['class'=>'btn btn-rose pull-right']) !!}
</div>
#if(count($csloads) > 0)
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th><input type="checkbox" id="options"></th>
<th>Driver Name</th>
<th>Company Name</th>
<th>Vehicle Vin Number</th>
<th>Origin</th>
<th>Destination</th>
<th>Package Type</th>
<th>Dimensions</th>
<th>Weight</th>
</tr>
</thead>
<tbody>
#foreach($csloads as $csload)
#if($csload->status_id == 1)
<tr>
<td>{‌{$csload->id}}</td>
<td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="{‌{$csload->status ? $csload->status->id == 2 : $csload->status->id == 1}}"></td>
<td>{!! Form::select('driver_id', ['' => 'Choose Driver Name'] + $driver, null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>'exampleFormControlSelect1'])!!}</td>
<td>{!! Form::select('company_id', ['' => 'Choose Company Name'] + $company, null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>'exampleFormControlSelect1'])!!}</td>
<td>{!! Form::select('vehicle_id', ['' => 'Choose Vehicle Vin Number'] + $vehicle, null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>'exampleFormControlSelect1'])!!}</td>
<td>{‌{$csload->from}}</td>
<td>{‌{$csload->to}}</td>
<td>{‌{$csload->package_type}}</td>
<td>{‌{$csload->length}}x{‌{$csload->width}}x{‌{$csload->height}}</td>
<td>{‌{$csload->weight}}</td>
</tr>
#endif
#endforeach
</tbody>
</table>
</div>
#else
<h1 class="text-center">No Loads Found</h1>
#endif
{!! Form::close() !!}
</div>
</div>
</div>
I am struck in the project kindly answer the question as soon as you can I shall be really obliged.
Thanks in advance
From Munish Rana
Love your Work
change 'method' => 'PATCH' to 'POST'
and add {{ method_field('PATCH') }} to form field like this
<form method="POST" action="your url" >
{{csrf_field()}}
{{ method_field('PATCH') }}
</form>

MethodNotAllowedHttpException in laravel-5.6

I am trying to submit the form with method 'POSt' but getting MethodNotAllowedHttpException I know some possible reason for getting this error and also searched on the internet for a possible solution. My project's all other forms are working fine except this one. I am not finding the reason why I am getting this common error. Would someone help me please to find out the solution?
form
<form action="{{ url('admin/checkout') }}" method="POST">
#csrf
<div class="row">
<div class="col-sm-6 offset-sm-3">
<label class="m-t-20">Now time</label>
<div class="input-group">
<input name="outtime" class="form-control" id="single-input" value="" placeholder="Now" required>
<span class="input-group-btn">
<button type="submit" id="check-minutes" class="btn waves-effect waves-light btn-warning">Check Out</button>
</span>
#if ($errors->has('outtime'))
<small class="error">{{ $errors->first('outtime') }}</small>
#endif
</div>
</div>
</div>
<br>
<table id="flow-table" class="display nowrap mytable" cellspacing="0" width="100%">
<thead>
<tr>
<th style="width: 15px;">#</th>
<th class="check">
<div class="checkbox">
<label>
<input type="checkbox" id="flowcheckall" />
<i class="input-helper"></i>
<span><strong> All</strong></span>
</label>
</div>
</th>
<th class="text-left">Name</th>
<th>Cord No</th>
<th>Section</th>
<th>Designation</th>
</tr>
</thead>
<tbody>
#forelse($employees as $employee)
<tr class="text-center">
<td>{{ $loop->index + 1 }}</td>
<td style="max-width: 30px;">
<div class="checkbox text-center">
<label>
<input type="checkbox" name="employee_id[]" class="check" id="checkall" value="{{ $employee->employee_id }}" />
<i class="input-helper"></i>
</label>
</div>
</td>
<td class="text-left">{{ $employee->name }}</td>
<td>{{ $employee->card_no }}</td>
<td>{{ ucwords($employee->section) }}</td>
<td>{{ ucwords($employee->designation) }}</td>
</tr>
#empty
#endforelse
</tbody>
</table>
</form>
web.php
#Admin Routes
Route::get('admin', 'Admin\LoginController#showLoginForm')->name('admin.login');
Route::post('admin', 'Admin\LoginController#login');
Route::post('admin-password/email', 'Admin\ForgotPasswordController#sendResetLinkEmail')->name('admin.password.email');
Route::get('admin-password/reset', 'Admin\ForgotPasswordController#showLinkRequestForm')->name('admin.password.request');
Route::post('admin-password/reset', 'Admin\ResetPasswordController#reset');
Route::get('admin-password/reset/{token}', 'Admin\ResetPasswordController#showResetForm')->name('admin.password.reset');
Route::group(['prefix' => 'admin', 'middleware' => ['auth:admin'], 'as' => 'admin.'], function () {
# Dashboard / Index
Route::get('home', array('as' => 'home','uses' => 'Admin\AdminController#index'));
Route::get('change-password', array('as' => 'change-password','uses' => 'Admin\AdminController#changePassword'));
Route::put('change-password', array('as' => 'change-password','uses' => 'Admin\AdminController#updatePassword'));
// HR (Section)
Route::resource('section', 'Admin\HR\SectionController');
// HR (Designation)
Route::resource('designation', 'Admin\HR\DesignationController');
// HR (Salary Grade)
Route::resource('salary-grade', 'Admin\HR\SalaryGradeController');
// HR (Employee)
Route::resource('employees', 'Admin\HR\EmployeeController');
//HR (Employee cv download)
Route::get('cv-download/{id}', 'Admin\HR\EmployeeController#cvDownload');
// HR (Attendance)
Route::resource('attendances', 'Admin\HR\AttendanceController');
Route::post('attendances/searched-employees', 'Admin\HR\AttendanceController#searchedEmployees');
Route::get('today-checked-in', array('as' => 'today-checked-in', 'uses' => 'Admin\HR\AttendanceController#checkedIn'));
Route::post('checkout', 'Admin\HR\AttendanceController#checkout');
//HR (Leave Type)
Route::resource('leave-types', 'Admin\HR\LeaveTypeController');
//HR (Leave Application)
Route::resource('leave-application', 'Admin\HR\LeaveApplicationController');
Route::post('leave-application/searched-employees', 'Admin\HR\LeaveApplicationController#searchedEmployees');
Route::get('leave-application/{id}/create', 'Admin\HR\LeaveApplicationController#create');
Route::get('leave-application-download/{id}', 'Admin\HR\LeaveApplicationController#applicationDownload');
//HR (Holidays)
Route::resource('holidays', 'Admin\HR\HolidayController');
//HR (Promotions)
Route::resource('promotions', 'Admin\HR\PromotionController');
Route::get('promotions/{id}/create', 'Admin\HR\PromotionController#create');
Route::post('promotions/searched-employees', 'Admin\HR\PromotionController#searchedEmployees');
Route::get('promotions/update/{id}', 'Admin\HR\PromotionController#');
//HR (Payroll Provident Fund)
Route::resource('provident-fund', 'Admin\HR\ProvidentFundController');
Route::post('provident-fund/searched-employees', 'Admin\HR\ProvidentFundController#searchedEmployees');
Route::get('provident-fund/{id}/create', 'Admin\HR\ProvidentFundController#create');
//HR (Payroll Advance Salary)
Route::resource('advance-salary', 'Admin\HR\AdvanceSalaryController');
Route::post('advance-salary/searched-employees', 'Admin\HR\AdvanceSalaryController#searchedEmployees');
Route::get('advance-salary/{id}/create', 'Admin\HR\AdvanceSalaryController#create');
//HR (Payroll-Salary)
Route::group(['prefix' => 'salary', 'as' => 'salary.'], function () {
//make salary
Route::get('make-salary', array('as' => 'make-salary', 'uses' => 'Admin\HR\SalaryController#makeSalaryIndex'));
Route::post('make-salary-employees-list', array('as' => 'make-salary-employees-list', 'uses' => 'Admin\HR\SalaryController#getMakeSalaryEmployeeList'));
Route::post('make-salary-save/{id}', array('as' => 'make-salary-save', 'uses' => 'Admin\HR\SalaryController#makeSalarySave'));
//make payment
Route::get('make-payment', array('as' => 'make-payment', 'uses' => 'Admin\HR\SalaryController#makePaymentSearch'));
Route::post('make-payment-employees-list', array('as' => 'make-payment-employees-list', 'uses' => 'Admin\HR\SalaryController#getMakePaymentEmployeeList'));
Route::get('employee/{id}', array('as' => 'employee', 'uses' => 'Admin\HR\SalaryController#makeEmployeeSalary'));
Route::put('change-payment-status/{id}', array('as' => 'change-payment-status', 'uses' => 'Admin\HR\SalaryController#changePaymentStatus'));
//generate payslip
Route::get('payslip', array('as' => 'payslip', 'uses' => 'Admin\HR\SalaryController#generatePayslip'));
Route::post('payslip-search', array('as' => 'payslip-search', 'uses' => 'Admin\HR\SalaryController#payslipSearch'));
});
/*Accounts Part*/
//Accounts (Groups)
Route::resource('groups', 'Admin\Accounts\GroupController');
//Accounts (Groups)
Route::resource('companies', 'Admin\Accounts\CompanyController');
//Accounts (Customers)
Route::resource('customers', 'Admin\Accounts\CustomerController');
//Accounts (Suppliers)
Route::resource('suppliers', 'Admin\Accounts\SupplierController');
});
AttendanceController.php
/**
*
*checkout
**/
public function checkout(Request $request)
{
return $request->all();
}
try this
Route::post('checkout', 'Admin\HR\AttendanceController#checkout')->name('checkout');
<form action="{{ route('admin.checkout') }}" method="POST">
Create a route in web.php file
Route::get('/', 'LoginController#index');
In Controller add
public function index(){
$postHeader = Request::header(); // HEADER Data
$postData = Request::all();
if(!empty($postData)){
echo'<pre>';print_r($postData); die;
}
}
Do not forget to add crf token in your View
<form name="" action="login" method="POST">
{{ csrf_field() }}

Laravel: Check checkbox if true or false, then update database

Just started with laravel using phpStorm. Im trying to create a form that take inputs, and a checkbox, then adds it to a database.
All of the rows in the database get listed in the view index.html. The user should be allowed to activate or deactivate (with the checkbox) the the message that should be listed when browsing the index.html file. Because if a news article is active, and you want to deactivate it, you should be able to just uncheck the checkbox, and it will be deactivated.
So I am wondering how my function should look like.
Im also unsure how to run the function ActivatedOrDeactivated when the checkbox gets checked or unchecked.
Its my first post, so please tell if something is hard to understand in my description.
My route:
Route::get('admin',
[
'uses' => 'NyhetsController#index',
'as' => 'admin.index'
]
);
Route::get('admin/create',
[
'uses' => 'NyhetsController#create',
'as' => 'admin.create'
]
);
Route::post('admin',
[
'uses' => 'NyhetsController#store',
'as' => 'admin.store'
]
);
Route::get('admin/{id}',
[
'uses' => 'NyhetsController#show',
'as' => 'admin.show'
]
);
Route::get('admin/{id}/edit',
[
'uses' => 'NyhetsController#edit',
'as' => 'admin.edit'
]
);
Route::put('admin/{id}',
[
'uses' => 'NyhetsController#update',
'as' => 'admin.update'
]
);
Route::get('admin/{id}/delete',
[
'uses' => 'NyhetsController#delete',
'as' => 'admin.delete'
]
);
Route::delete('admin/{id}',
[
'uses' => 'NyhetsController#destroy',
'as' => 'admin.destroy'
]
);
My Controller that contains the function (just something i wrote in anger):
public function ActivatedOrDeactivated($id){
$news = News::findOrFail($id);
$input = Input::get('active');
if($input == true)
{
$news->active = 'false';
$news->update($input);
}
else{
$news->active = 'true';
$news->update($input);
}
}
My index file that contains the form:
<h1>Alle postene i databasen</h1>
<p>{{ link_to_route('admin.create', 'Legg til ny nyhet') }}</p>
#if($news->count())
<table class="table table-striped table-boarded">
<thead>
<tr>ID</tr>
<tr>Title</tr>
<tr>Author</tr>
<tr>Message</tr>
<tr>Active</tr>
<tr>Picture path</tr>
<tr>Activate/Deactivate</tr>
</thead>
<tbody>
#foreach($news as $n)
<tr>
<td>{{ $n->id }}</td>
<td>{{ $n->title }}</td>
<td>{{ $n->author }}</td>
<td>{{ $n->message }}</td>
<td>{{ $n->active }}</td>
<td>{{ $n->picture_path }}</td>
<td>{{ Form::checkbox('active') }}</td>
<td>{{ link_to_route('admin.destroy', 'Delete', array($n->id)) }}</td>
</tr>
#endforeach
</tbody>
</table>
When you want to update the news item when a user clicks the checkbox without ajax this would a way to do it:
router.php
Route::post('admin/{id}/active',
[
'uses' => 'NyhetsController#toggleActive',
'as' => 'admin.toggle_active'
]
);
HTML index.blade.php
#if($news->count())
<table class="table table-striped table-boarded">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Message</th>
<th>Picture path</th>
<th>Active</th>
</tr>
</thead>
<tbody>
#foreach($news as $n)
<tr>
<td>{{ $n->id }}</td>
<td>{{ $n->title }}</td>
<td>{{ $n->author }}</td>
<td>{{ $n->picture_path }}</td>
<td>{{ $n->message }}</td>
<td>
{{ Form::open(array('url' => 'admin/' . $n->id . '/active')) }}
{{ Form::submit('', [ 'class' => ($n->active ? 'glyphicon glyphicon-ok' : 'glyphicon glyphicon-remove') ]);
{{ Form::close() }}
<td>{{ link_to_route('admin.destroy', 'Delete', array($n->id)) }}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
NyhetsController
public function toggleActive($id) {
$news = News::findOrFail($id);
if($news->active)
{
$news->active = 'false';
$news->update($input);
}
else{
$news->active = 'true';
$news->update($input);
}
}
return Redirect::to('admin');
Code is untested!
In your Form::
{{ Form::checkbox('active', 'true') }}
In your Controller
$news = News::findOrFail($id);
if (Input::get('active') === 'true') {
$news->active = 'true'; // UPDATE:must be true of course
$news->update($input);
} else {
$news->active = 'false'; // UPDATE:must be false of course
$news->update($input);
}
By the way: you could save yourself some typing if you simply route restfully using
Route::resource('admin', 'NyhetsController');

Categories