Why my form is not sending data with POST in Laravel? - laravel

I'm creating my login page with Laravel
I want send my login form datas with POST method, but is not working
// /view/login.blade.php
/*
{{ Form::open([
"route" => "user/login",
"autocomplete" => "off",
'method' => 'POST'
]) }}
{{ Form::label("username", "Usuário:") }}
{{ Form::text("username", Input::old("username"), [
"placeholder" => "john.smith"
]) }}
{{ Form::label("password", "Senha:") }}
{{ Form::password("password", [
"placeholder" => "*******"
]) }}
{{ Form::submit("Entrar") }}
{{ Form::close() }}
//---------------------------------------
// routes.php
Route::any( '/', [
"as" => "user/login",
"uses" => "UserController#loginAction"
] );
//---------------------------------------
// /controllers/UserController.php
class UserController extends Controller
{
public function loginAction()
{
echo Input::server( "REQUEST_METHOD" ); // This line is ever print "GET"
return View::make( 'user/login' );
}
}*/
[Code edited]
// view/login.blade.php
<form action="{{URL::to('/')}}" method="post">
<input name="login" type="text"/><br/>
<input type="password" name="senha" id=""/><br/>
{{ Form::submit('Enviar') }}
</form>
// routes.php
Route::any('/', function()
{
echo Request::getMethod(); is returning GET forever
return View::make( 'login' );
});
Apparently, my form will send datas with POST method, but I can never get they in $_POST, why?

You should use:
Input::all()
to get all the data
or Input::get('username'), Input::get('password') and so on to get selected data.

Related

How to update user status using button without update all parameters in laravel

i want to update status user just pass parameter of 'status'.
this is my code, but i don't know, why i can not update user status. how to fix this problem?
my controller
public function activation()
{
// dd('test');
$action = Input::get('status');
if (Input::get('activate'))
{
$this->activateUser($action);
}
elseif (Input::get('inactivate'))
{
$this->deactivateUser($action);
}
return redirect(route('admins-users.index'))->with('message-post', 'Status was updated successfully');
}
public function activateUser($user)
{
//dd('active');
User::findOrNew($user)->update(['status' => "1"]);
}
public function deactivateUser($user)
{
// dd('nonactive');
User::findOrNew($user)->update(['status' => "0"]);
}
my route
Route::post('admins-users/status', 'Backend\StatusController#activation');
my view
{!! Form::open(array('url' => 'admins-users/status')) !!}
#if ($user->status)
{!! Form::submit('inactivate', ['name' => 'inactivate', 'class'=>'btn btn-xs btn-default']) !!}
#else
{!! Form::submit('Activate', ['name' => 'activate', 'class'=>'btn btn-xs btn-success']) !!}
#endif
{!! Form::close() !!}
After trying several ways. finally, i was found the answer for this problem using Ajax and select option. i add hash id before pass to controller and decode again in controller. i thinks id that pass must be concerned.
my controller
public function control(Request $request){
$status = $request->status;
$iduser = $request->iduser;
$key = Hashids::connection('main')->decode($iduser)[0] ?? abort(404);
$update = User::where('id', $key)->update(['status'=> $status]);
if($update)
{
return redirect(route('admins-users.index'))->with('message-post', 'Status user was updated successfully');
}
}
my form
using hash id to encode id user
#php $parameter = Hashids::connection('main')->encode($user->id); #endphp
{!! Form::hidden(null,$parameter, ['id'=> 'iduser'.$parameter ])!!}
{!! Form::select(
'status',
array(1=>'Active',0=>'Not Active'),
$user->exists ? $user->status : null,
[
'id' => 'action'.$parameter,
'placeholder' => 'Choose a status'
]
)
!!}
script
$(document).ready(function(){
#foreach($users as $user)
#php $parameter = Hashids::connection('main')->encode($user->id); #endphp
$("#action{{ $parameter }}").change(function(){
var status = $("#action{{ $parameter }}").val();
var iduser = $("#iduser{{ $parameter }}").val();
if(status==""){
alert("Please select an option");
}
else{
if (confirm('Do you want to change {{ $user->name }} status to {{ $user->status ? 'InActive' : 'Active' }}?')) {
$.ajax({
url: '{{ url("/action") }}',
data: 'status=' + status + '&iduser=' + iduser,
type: 'get',
success:function(response){
console.log(response);
}
});
document.location.reload();
}
}
});
#endforeach
});
Try with this
{!! Form::open(['url' => 'admins-users/status', 'method' => 'get' !!}
<input type="hidden" name="user_id" value="{{ $user->id }}">
#if ($user->status)
{!! Form::submit('inactivate', ['name' => 'inactivate', 'class'=>'btn btn-xs btn-default']) !!}
#else
{!! Form::submit('Activate', ['name' => 'activate', 'class'=>'btn btn-xs btn-success']) !!}
#endif
{!! Form::close() !!}
Your route
Route::get('admins-users/status', 'Backend\StatusController#activation');
Your Controller Method
public function activation(Request $request)
{
$user_id = $request->user_id
if ($request->acticate) {
$this->activateUser($user_id);
}
elseif ($request->inactiavte) {
$this->deactivateUser($user_id);
}
return redirect(route('admins-users.index'))->with('message-post', 'Status was updated successfully');
}
Hope this helps :)

Update Data in Laravel

This is my code :
Route:
Route::get('/editposts/{id}', function ($id) {
$showpost = Posts::where('id', $id)->get();
return view('editposts', compact('showpost'));
});
Route::post('/editposts', array('uses'=>'PostController#Update'));
Controller :
public function Update($id)
{
$Posts = Posts::find($id);
$Posts->Title = 10;
$Posts->Content = 10;
$Posts->save();
//return Redirect()->back(); Input::get('Title')
}
and View:
#foreach($showpost as $showpost)
<h1>Edit Posts :</h1>
{{ Form::open(array('url'=>'editposts', 'method'=>'post')) }}
Title : {{ Form::text('Title', $showpost->Title) }} <br> Content : {{ Form::text('Content', $showpost->Content ) }} <br> {{ Form::submit('Update') }}
{{ Form::close() }}
#endforeach
but when I want to Update my data i receive an error :
http://localhost:8000/editposts/1
Missing argument 1 for App\Http\Controllers\PostController::Update()
You need to change route:
Route::post('editposts/{id}', 'PostController#Update');
Then the form to:
{{ Form::open(['url' => 'editposts/' . $showpost->id, 'method'=>'post']) }}
Change your post route to:
Route::post('/editposts/{id}', 'PostController#Update');
Done!
Correct the route,specify a parameter
Route::post('editposts/{id}', 'PostController#Update');
Pass the post'id as paramater
{{ Form::open(array('url'=>'editposts/'.$post->id, 'method'=>'post')) }}
Title : {{ Form::text('Title', $showpost->Title) }} <br> Content : {{ Form::text('Content', $showpost->Content ) }} <br> {{
Form::submit('Update') }}
{{ Form::close() }}
Notice $post->id
First declare your route:
Route::post('/editposts/{id}', array('uses'=>'PostController#Update'));
Then update your form url:
{{ Form::open(['url' => url()->action('PostController#Update', [ "id" => $showpost->id ]), 'method'=>'post']) }}
This is assuming your model's id column is id
(Optional) You can also use implicit model binding :
public function Update(Posts $id) {
//No need to find it Laravel will do that
$id->Title = 10;
$id->Content = 10;
$id->save();
}

Submit form, add input to URL

I have a regular form with a single input:
{{ Form::open(array('id' => 'form_search')) }}
<div class="form-group">
{{ Form::text('search', '', array('class' => 'form-control', 'placeholder' => 'Search...')) }}
</div>
{{ Form::close() }}
When the form is submitted, I want it to redirect to a page showing the results by the following URL:
http://www.website.com/search/<QUERY_HERE>
For example, if someone typed john in the form input and submitted the form, the URL redirected to would look like:
http://www.website.com/search/john
How can I do this?
In your routes.php
//Handle form submit
Route::get('search', 'YourSearchController#yourSearchFunction');
//Return results
Route::get('search/{search}', 'YourSearchController#yourSearchResults');
Then add the route to your form:
{{Form::open(['route' => 'search'])}}
Then in yourSearchController:
function yourSearchFunction() {
$search = Input::only(['search']);
return Redirect::to('search/'.$search);
}
Then also in yourSearchController:
function yourSearchResults($search) {
return View::make('results')->with(compact('search'));
}

How to create remember me action using laravel auth

i have a checkbox with my login form , which will remember user when checked . I am using following code but it doesnot works for me :
VIEW :
#extends('layouts.main')
#section('title') Dashboard
#stop
#section('content')
{{ Form::open(array('url'=>'users/signin', 'class'=>'form-signin')) }}
<h2 class="form-signin-heading">Please Login</h2>
{{ Form::text('email', null, array('class'=>'input-block-level', 'placeholder'=>'Email Address')) }}
{{ Form::password('password', array('class'=>'input-block-level', 'placeholder'=>'Password')) }}
{{ Form::checkbox('remember_me','false',false,array('class'=>'input-block-level')) }}
{{ Form::submit('Login', array('class'=>'btn btn-large btn-primary btn-block'))}}
{{ Form::close() }}
#stop
CONTROLLER :
public function postSignin() {
if (Auth::attempt(array('email'=>Input::get('email'), 'password'=>Input::get('password'),'active' => 1),Input::has('remember_me'))) {
return Redirect::to('users/dashboard')->with('message', 'You are now logged in!');
} else {
return Redirect::to('users/login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}
Please help me out on this , This function does not remembers user .
If you have some better code then please tell me that .
Thanks.
if you want to remember a user pass the third parameter true
if (Auth::attempt(array('email' => $email, 'password' => $password), true))
{
// The user is being remembered...
}
Your code:
public function postSignin() {
$rememberMe = false;
if(Input::has('remember_me')) {
$rememberMe = true;
}
if (Auth::attempt(array('email'=> Input::get('email'), 'password'=> Input::get('password') ), $rememberMe )) {
return Redirect::to('users/dashboard')->with('message', 'You are now logged in!');
} else {
return Redirect::to('users/login')
->with('message', 'Your username/password combination was incorrect')
->withInput();
}
}

Laravel pre-filling multiple forms if validation failed

One of the coolest Laravel feature is, Laravel pre-filled the form fields if validation error occurred. However, if a page contain more than one form, and form fields have same name, Laravel pre-filling all forms fields.
For example:
I have a page where i have two forms to create new users or whatever.
<h1>Create user1</h2>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => 'foo/bar')) }}
{{ Form::text('name', null) }}
{{ Form::email('email', null) }}
{{ Form::close() }}
Controller
class UsersController extends BaseController
{
public function store()
{
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails()) {
return Redirect::back()->withInput()->withErrors($validation);
}
}
}
As i didn't fill up the email, Laravel will throw validation error and pre-filling the forms as following:
How to tell Laravel that do not fill-up the second form?
There's no Laravel way of doing this, but you can use HTML basic form arrays to make it work. You need to understand that you have to identify your forms and fields so Laravel knows exactly where the data came from and where to send it back to. If all your fields have the same name how could it possibly know?
This is a proof of concept that will work straight from your routes.php file.
As I did it all and tested here before posting the answer I used Route::get() and Route::post(), to not have to create a controller and a view just to test something I will not use. While developing this you will have to put this logic in a controller and in a view, where I think they are alredy in.
To test it the way it is, you just have to point your browser to the following routes:
http://yourserver/form
and when you push a button it will automatically POST tho the route:
http://yourserver/post
I'm basically giving all forms a number and giving the buttons the number that we will usin in Laravel to get the form data and validate it.
Route::get('form', function()
{
return Form::open(array('url' => URL::to('post'))).
Form::text('form[1][name]', null).
Form::email('form[1][email]', null).
'<button type="submit" name="button" value="1">submit</button>'.
Form::close().
Form::open(array('url' => URL::to('post'))).
Form::text('form[2][name]', null).
Form::email('form[2][email]', null).
'<button type="submit" name="button" value="2">submit</button>'.
Form::close();
});
And here we get the data, select the form and pass all of it to the validator:
Route::post('post', function()
{
$input = Input::all();
$rules = [
'name' => 'required',
'email' => 'required'
];
$validation = Validator::make($input['form'][$input['button']], $rules);
return Redirect::back()->withInput();
});
This is how you use it in a Blade view, now using 3 forms instead of 2 and you can have as many forms as you need:
<h1>Create user1</h2>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[1][name]', null) }}
{{ Form::email('form[1][email]', null) }}
<button type="submit" name="button" value="1">submit</button>
{{ Form::close() }}
</h1>Create user2</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[2][name]', null) }}
{{ Form::email('form[2][email]', null) }}
<button type="submit" name="button" value="2">submit</button>
{{ Form::close() }}
</h1>Create user3</h1>
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text('form[3][name]', null) }}
{{ Form::email('form[3][email]', null) }}
<button type="submit" name="button" value="3">submit</button>
{{ Form::close() }}
And you can even use a loop to create 100 forms in blade:
#for ($i=1; $i <= 100; $i++)
User {{$i}}
{{ Form::open(array('url' => URL::to('post'))) }}
{{ Form::text("form[$i][name]", null) }}
{{ Form::email("form[$i][email]", null) }}
<button type="submit" name="button" value="{{$i}}">submit</button>
{{ Form::close() }}
#endfor
Use old input with $request->flash().
https://laravel.com/docs/5.2/requests#old-input

Resources