php change certain rows value with a button - php

I have abstracts table in my database with the Abstract_Status_ID column, I am trying to create a button that changes every Status from '2' to '3'
I have tried to do this:-
My controller
public function publish($A_ID)
{
$abstracts = Project::find($A_ID);
$abstracts->Abstract_Status_ID= 3;
$abstracts->save();
return redirect('/AdvertisedProjects')->with ('success', 'Abstracts Published' );
}
my route
Route::put( '/projects', 'AbstractsController#publish');
Route::post( '/projects', 'AbstractsController#publish');
my view (projects)
Tried with the csrf token and without as eloquent docs says any post/put will be restricted without it.
#if (count ($abstracts)> 0)
#foreach ($abstracts as $abstract)
#if($abstract->Abstract_Status_ID == 2)
{!! Form::open(['action' => ['AbstractsController#publish' , $abstract->A_ID], 'method' => 'post' ]) !!}
{{ csrf_field() }}
{{Form::hidden('_method', 'PUT') }}
{{Form::Submit('Submit Changes',['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
#endif
#endforeach
The error I am getting when clicking the button
(1/1) ErrorException
Missing argument 1 for App\Http\Controllers\AbstractsController::publish()
Also, the code above will show more than one button, any suggestions to make one button change all of them ?

A: If you want to have a button for each ABSTRACTS just change your route to :
Route::put( '/projects/{A_ID}', 'AbstractsController#publish');
B: If you want to have only one button that change all , you can echo their ID in hidden input then send form
so your view would be:
#if (count ($abstracts)> 0)
{!! Form::open(['action' => ['AbstractsController#publish'], 'method' => 'post' ]) !!}
{{ csrf_field() }}
{{Form::hidden('_method', 'PUT') }}
#foreach ($abstracts as $abstract)
#if($abstract->Abstract_Status_ID == 2)
{{Form::hidden('abstract_ids[]', $abstract->A_ID) }}
#endif
#endforeach
{{Form::Submit('Submit Changes',['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
And Your Controller :
public function publish()
{
foreach(request('abstract_ids') as $A_ID){
$abstracts = Project::find($A_ID);
$abstracts->Abstract_Status_ID= 3;
$abstracts->save();
}
return redirect('/AdvertisedProjects')->with ('success', 'Abstracts Published' );
}

You are using form method="POST". I think it should be method="PUT".

The main problem in your code is the definition of your routes, You are passing an argument ($A_ID) to the controllers publish method,
But in your routes, you did never mention that you are passing any argument through your route. So for passing the argument, you can use {$A_ID} in your route URL.
One thing you should always remember is that you should always give your route a name and call it by using its name and route() Laravel helper method.
The benefit of using route name is that if you decide to change the URL-Structure of your route later in the development process, you'll never have to change it everywhere in your application because you did not call it by its URL.
And route name is less error prone
In total, You should define your routes like this
Route::put('projects/{A_ID}/update', 'AbstractsController#publish')->name('projects.update');
Route::post('projects/{A_ID}/post', 'AbstractsController#publish')->name('projects.store');
Then in you blade files now you can call it like
{!! Form::open(['action' => route('projects.store', $abstract->A_ID), 'method' => 'post' ]) !!}
Hope this will clarify and resolve your problem.

Related

Laravel Routes not working for specific cases

any expert here ? This is a very strange problem I am facing.
I have my website hosted on an aws machine. The code was working absolutely fine there. Then it was shifted to another server and this strange problem staeted to appear.
I have a route to update a car
Route::put('vehicles/{vehicle}', 'VehicleController#update');
Edit form
{!! Form::model($vehicle, ['url' => ['backend/vehicles', $vehicle->id], 'method' => 'put','files' => true , 'class' => 'form-horizontal form-label-left', 'role' => 'form']) !!}
#include( 'backend.vehicles.form' )
{!! Form::close() !!}
Now here is where the strange behaviour start, whenever I try to update a car which was created prior to the server move, It shows me MethodNotAllowedHttpException in RouteCollection.php
But when I create a car and then updates this new car, Operation succeeds. Please help.
One more thing, In routeCollection.php where it matches a route for a request, It shows GET method for old car but put method for new car
public function match(Request $request){
// die($request->getMethod()); $routes = $this->get($request->getMethod());
$route = $this->check($routes, $request);
if (! is_null($route)) {
return $route->bind($request);
}
// If no route was found we will now check if a matching route is specified by
// another HTTP verb. If it is we will need to throw a MethodNotAllowed and
// inform the user agent of which HTTP verb it should use for this route.
$others = $this->checkForAlternateVerbs($request);
if (count($others) > 0) {
return $this->getRouteForMethods($request, $others);
}
throw new NotFoundHttpException;
}
Please anyone.
Add this inside the form
{{ method_field('PUT') }}
or in HTML
<input type="hidden" name="_method" value="PUT">
Please try the following solution:
Route::put('vehicles/{vehicle}', 'VehicleController#update');
Change to
Route::match(['put', 'patch'], 'vehicles/{vehicle}', 'VehicleController#update');
And the form to
{!! Form::model($vehicle, ['action' => ['VehicleController#update', $vehicle->id], 'method' => 'put','files' => true , 'class' => 'form-horizontal form-label-left', 'role' => 'form']) !!}
#include( 'backend.vehicles.form' )
{!! Form::close() !!}
Does it work for you?

Laravel get data from dropdown list and pass it to the controller

I am trying to have the user choose a month from a dropdown list displaying the months, and passes that month value (in numbers) to the controller
I am having trouble making the dropdown list an action so once the user picks the month, the controller gets called.
here is my index page:
<h>Display a logs by monthly <h>
{{ $id=Form::selectMonth('month')}}
<a href="{{action('LogController#monthly',['id' => $id]) }}" class="btn btn-primary">Monthly Logs
</a>
and when I add the Form method inside the tag i am getting an error says the variable is not defined.
here is the Controller.php
public function monthly($id)
{
$dcmlogs = log::with('users')
->whereMonth('created_at', '=', $id)
->paginate(15);
return view('dcmlog.index', compact('dcmlogs'));
}
You can use something like this :
{!! Form::open(['route' => ['logs', $id], 'method' => 'POST' ])!!}
{{ Form::select('in_out',[1 => 'Jan', 2 => 'Feb'] , null, ['class'=>'
form-control'])
}}
{!! Form::close() !! }}
hope this helps ..
I recommend creatintg a route
Route::get('/logs/{id}', 'LogController#monthly')->name('logs');
And use the route function in the template:
route('logs', ['id'->$id]);

Passing String between views - Laravel 5.1

I want to create a two buttons buyer and seller in the home page, and on click of these buttons, I want the guest to get directed register page with a ~hidden input~ placed in the form depending on the value of the button pressed.
I am using Laravel 5.1
For what I am trying to achieve, do I need to register a new route and a new function?
First, do I need to use a {!! link_to !!} or {!! Form submit !!}. I thought form submit would work:
{!! Form::open(array('url' => '/auth/register', 'profession' => 'seller')) !!}
{!! Form::submit('Seller', array('class' => 'btn btn-warning')) !!}
{!! Form::close() !!}
My routes are:
Route::get('auth/register', 'Auth\AuthController#getRegister');
Route::post('auth/register', 'Auth\AuthController#postRegister');
auth/register and AuthController is the one that comes with Laravel default. I also didn't register a new public function. Is this the reason? Do I need to send the data from view to controller and then other view (view->controller->view). I am really confused on this one.
This is how it seems in the view-source:
<form method="POST" action="http://app.com/auth/register" accept-charset="UTF-8" profession="seller"><input name="_token" type="hidden" value="Cw4Het1A1M6020oQL45Cy2Q0ct46TSe6ba2g4r4C">
<input class="btn btn-warning" type="submit" value="Seller">
</form>
Edit:
I think I can't send variables between views. So do I need to register a completely new route and a controller, and two methods in it? I am really confused on this stage.
Check out my answer to your previous similar question for details on the implementation:
Laravel Passing Data From One View to Another View
To answer the questions you are posing
You can use two forms one for buyer and one for seller
{!! Form::open(['route' => ['type_path']]) !!}
{!! Form::hidden('type', 'buyer') !!}
{!! Form::submit('Buyer', array('class' => 'btn btn-warning')) !!}
{!! Form::close() !!
{!! Form::open(['route' => ['type_path']]) !!}
{!! Form::hidden('type', 'seller') !!}
{!! Form::submit('Seller', array('class' => 'btn btn-warning')) !!}
{!! Form::close() !!
on your landing page and then have both of this forms direct to a same named route (in this case 'type_path')
Then in your routes.php file you would reference only one controller and one method and handle the logic in that method. Again see the link to my answer to see a full implementation of this for the example of writer and reader.
Essentially as you say, you'd be sending as the hidden inputs from the view to the controller to the second view.
You could register a new route like:
Route::get('auth/{TYPE}/register', 'Auth\AuthController#getRegisterType')
Your home page would have something like this:
seller
Your controller method would be something like this:
public function getRegisterType($type)
{
Session::put('registerType', $type);
return redirect('/auth/register');
}
Then you can access you set session variable from the controller methods getRegister & postRegister
Have you two buttons direct to the register page with a query string parameter:
Buyer
Seller
And then just check for the query string parameter in your register.blade.php view:
{!! Form::hidden('account_type', Request::query('type')) !!}
If you need to validate one of the two is present, then you could create a middleware class you apply to the login route only:
public function handle($request, Closure $next)
{
if (! in_array($request->query('type'), ['buyer', 'seller'])) {
// Error
}
return $next($request);
}

Laravel4: delete a comment

I have a simple blog with Post resource and Comment nested resource.
Until now I can see all the comments belonging to a post and create a new comment for a post.
I want to give the possibility to delete a specific comment, but somehow I am making some mistakes.
This is the view comments.index with all the comments:
#extends('master')
#section('blog')
#foreach($comments as $comment)
<div class="span11 well">
<ul>
<li><strong>Body: </strong> {{ $comment->body }} </li>
<li><strong>Author: </strong> {{ $comment->author }}</li>
</ul>
{{ Form::open(array('method' => 'DELETE', 'route' => array('posts.comments.destroy', $post_id), $comment->id)) }}
{{ Form::submit('Delete', array('class' => 'btn btn-danger')) }}
{{ Form::close() }}
</div>
#endforeach
{{ link_to_route('posts.index', 'Back to Post index') }}
This is the error i get running the index: Parameter "comments" for route "posts.comments.destroy" must match "[^/]++" ("" given) to generate a corresponding URL.
This is the Index method inside CommentsController:
public function index($post_id)
{
$comments = Post::find($post_id)->comments;
return View::make('comments.index', compact('comments'))->with('post_id', $post_id);
}
And this is the Destroy method inside CommentsController:
public function destroy($post_id, $comment_id)
{
$comment = $this->comment->find($comment_id)->delete();
return Redirect::route('posts.comments.index', $post_id);
}
Someone can tell me please where I am making the mistake?
This the routes:
Route::resource('posts', 'PostsController');
Route::resource('posts.comments', 'CommentsController');
You have put a regexp tester on your route, to check your comments parameter.
This error message says that parameter that you give to Laravel isn't good.
If your parameter is only a decimal id, use \d+ regexp instead.
Without your routes.php file - I cant be sure, but I think this might be the problem.
Change
{{ Form::open(array('method' => 'DELETE', 'route' => array('post.comments.destroy', $post_id), $comment->id)) }
to
{{ Form::open(array('method' => 'DELETE', 'route' => array('post.comments.destroy', array ($post_id, $comment->id))) }
If this does not work - please post your routes.php file.
Edit: You have defined your route as a "resource". This means your destroy route is defined with only one variable. You dont actually need the $post included, so just define this:
{{ Form::open(array('method' => 'DELETE', 'route' => array('posts.comments.destroy', $comment->id))) }}
and change your destroy method to this - there is no need for the $post to delete a $comment:
public function destroy($comment_id)
{
$comment = $this->comment->find($comment_id)->delete();
return Redirect::back();
}

Laravel: how do I pass a value from a form to a controller?

I have a form:
{ Form::open(array('action' => 'RatesController#postUserRate', $client->id)) }}
{{ Form::text('rate', '', array('placeholder' => 'Enter new custom client rate...')) }}
{{ Form::submit('Submit', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
How do I pass my $client->id value through the form to my controller method?
I currently have a controller method that looks like this:
public function postUserRate($id)
{
$currentUser = User::find(Sentry::getUser()->id);
$userRate = DB::table('users_rates')->where('user_id', $currentUser->id)->where('client_id', $id)->pluck('rate');
if(is_null($userRate))
{
...
}else{
....
}
}
And the error log says "Missing argument 1 for RatesController::postUserRate()"
Any ideas on how to pass this $client->id into my controller so I can use it as I want to above?
Add {{ Form::hidden('id', $client->id) }}to the form. Then, when it's posted, you can fetch its value per usual with Input::get('id').
Also, remove the postUserRate method's argument.
You simply use :
Form::open(array('action' => array('Controller#method', $user->id)))
the variable $user->id is passed as argument to the method method, also this last one should recieve an argument as well, like so : method($userId)
Source : Laravel documentation

Categories