Laravel insert into mysql db from a controller function - laravel

I am trying to submit records into a mysql table with many fields by using a Laravel .blade.php view ( php form)
I made some trials but I get
FatalErrorException in loginController.php line 54: Class 'App\Http\Controllers\Input' not found.
Mysql
create table users(id int primary key auto_increment,username varchar(20),password varchar(20),createDate timestamp );
My controller function
public function formSubmit()
{
if (Input::post())
{
$username = Input::get('username');
$password = Input::get('password');
DB::table('users')->insert(array ('username' => $username,'password' => $password));
return View::make('view2')->with(array('username' =>$username, 'password' => $password));
}
}
view1.blade.php form
<form action="{{url('/view2') }}" method="POST">
{{ csrf_field() }}
<input type ="hidden" name="">
User name: <input type ="text" name="username"> <br/>
Password <input type="password" name="password"> <br/>
<input type="submit" name="formSubmit" value="formSubmit">
</form>
Route
Route::get('/view1', 'loginController#formSubmit');

Add use Input; to the top of your class right after namespace clause.
Or use full namespace:
$username = \Input::get('username');
$password = \Input::get('password');
Or you just could use only() method to get an array from request:
DB::table('users')->insert(request()->only('username', password));
Also, never save raw passwords. Use bcrypt() to encrypt passwords.

Since you're using Laravel 5, use the Request Facade and acces input this way:
Request::input()
instead of using Input();
https://laravel.com/docs/5.0/requests
And, just in case, include it at the top of the Controller with
use Illuminate\Support\Facades\Request;

Referring to Amarnasan answer I used request and include use Illuminate\Http\Request; at the top of my controller.
So I changed my controller method to
public function formSubmit(Request $req)
{
$username =$req->input('username');
$password =$req->input('password');
DB::table('users')->insert(array ('username' => $username,'password' => $password));
return view ('view2')->with(array('username' =>$username, 'password' => $password));
}
}
and I changed my routes according to Shubham pokhriyal commit to:
Route::post('/view2', 'loginController#formSubmit');
Route::get('view1',function()
{
return view('view1');
}
);
and it works fine.

Related

How to auth user for login in laravel using auth()

i have started learning laravel and i am trying to create login.
i have tried this
route
Route::post('userLogin', [\App\Http\Controllers\LoginController::class,'userLogin'])->name('userLogin');
blade.php
<form role="form" method="POST" action="{{ route('userLogin') }}">
#csrf
.........
</form>
controller
<?php
namespace App\Http\Controllers;
use App\Models\Login;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class LoginController extends Controller
{
public function userLogin(Request $request){
$email = $request['email'];
$pass = $request['pass'];
if (auth()->attempt(['u_email' => $email, 'u_pass' => $pass])){
print 'ok';
}
else{
print 'none';
}
}
}
Problem
it is showing none, i have tried to print the values before auth() it print correct values.
Any solution
Use email and password instead of u_email and u_pass
You must pass the password as the field named 'password' in the credentials passed to Auth::attempt. This does not directly relate to the field in the table but the system needs to know what field in the credentials is the password so it can not include it in the query and then do a hash check against it if it finds a record. All the credentials passed to attempt except the 'password' field are where conditions on the query.
If you need to adjust what the password field is for that model you must adjust it on the model using the getAuthPassword method.

How to redirect back to preivous template with both input and collections of Eloquent in Laravel?

I need to pass both input and collections, that this controller produce, to the previous template. I try to use:
return redirect()->back->withInput()->with('userdata',$userdata);
but get undefined variable when access $userdata in template. This is controller:
public function inquireUpdateProcess(){
$input = request()->all();
$userdata = AuthorityKind::where('authority', $input['authority'])->first();
return redirect()->back->withInput()->with('userdata',$userdata);
}
And this is template of view:
<label for="text-authority-change">name of authority:</label>
<input type="text" name="authority_name_change" class="form-control"
value="{{$userdata->authority_name}}" />
I use the following instead then it works. But the outcome is couldn't pass the input data and collection in the same time, I know there must be a way to use return redirect()->back()... and get both previous input and the collection in template.
$userdata = AuthorityKind::where('authority', $input['authority'])->first();
$binding = [
'title' => 'Authority management',
'userdata' => $userdata,
];
return view('authority.authView', $binding);
I found out the data put into with() can only get it by session in template of blade like this :
<input type="text" id="text-authority-change" name="authority_name_change" class="form-control"
value="{{session()->get('userdata')['authority_name']}}"
/>
Even the collections of Eloquent are the the same way to access.

how do i pass data value to another page via link in laravel?

i am trying to make a list of locations that you can rent. but to rent the place you need to fill in some information. to fill in this information you excess another page. how do i make it so laravel knows the page belongs to a certain location
this is what ive done now but i keep getting the error:
Call to undefined method App\Reservation::location()
as soon as i have filled in the fields of information
this is the blade file that links to the the create reservation file
#foreach
($locations as $location => $data)
<tr>
<th>{{$data->id}}</th>
<th>{{$data->name}}</th>
<th>{{$data->type}}</th>
<th><a class="btn" href="{{route('Reservation.index', $data->id)}}">rent</a></th>
</tr>
#endforeach
this is the create reservations blade
<form action="{{ route('location.store') }}" method="post">
#csrf
<label>title</label>
<input type="text" class="form-control" name="name"/>
<label>type</label>
<select>
<option value="0">klein</option>
<option value="1">groot</option>
</select>
<button type="submit" class="btn">inschrijven</button>
</form>
this is what the location controller looks like
public function store(Request $request)
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($request->location());
$location->save();
return redirect('/location');
}
and the relationships in my models should also work
class Reservation extends Model
{
public function locations()
{
return $this->belongsTo('Location::class');
}
}
class Location extends Model
{
public function reservations()
{
return $this->hasMany('Registration::class');
}
}
ive been stuck at this all day and i really dont know where to look anymore
The error you are getting is because of the wrong function name, you are calling location, while it is locations.
public function locations(){}
&
$location->location()->associate($request->location());
and you can pass the variable as a query parameter, you'll need to pass this data as an array in your blade file.
Web.php
Route::get('/somewhere/{id?}, function(){
//do something
})->name('test');
Blade
route('test', ['id' => $id]);
Controller Method
public function store(Request $request, $id) //Adding the query parameter for id passed in Route.
{
$location = new Reservation;
$location->name = $request->get('name');
$location->type = $request->get('type');
$location->location()->associate($id);
$location->save();
return redirect('/location');
}

laravel 5.3 old input values always empty

see docs here about old input
Route::post('/search/all/', function (Request $request) {
//...
$products = $query->paginate(15);
$data = ['products' => $products,
'oldinput' => $request->all()];
return view('inventory.search_products', $data);
});
in the view:
this works:
<input type="text" id="search_all" name="search_all" value="{{ $oldinput['search_all'] }}">
this is always empty:
<input type="text" id="search_all" name="search_all" value="{{ old('search_all') }}">
Just call flush in your controller then you can use old() helper function in your blade.
public function YourController(Request $request){
$request->flash();
return view('yourblade');
}
In blade file:-
<input id="lng" name="lng" value="{{old('lng')}}" type="hidden">
docs says you should flash() then call old() method.
flashing stores the previous request in the session. so it makes sense that old(search_all) doesn't work
I will suggest the following solution:
return view('inventory.search_products', $data)->withInput(\Input::all());
And in blade you can call as well \Input::old('search_all');.

Custom Validator/Constraint with Arguments/Parameters in Symfony 2

I want to create a validator similar to the way GitHub handles deleting repositories. To confirm the delete, I need to enter the repo name. Here I want to confirm delete by entering the entity property "name". I will either need to pass the name to the constraint or access it in some way, how do I do that?
you could indeed use a validator constraint to do that:
1: Create a delete form (directy or using a type):
return $this->createFormBuilder($objectToDelete)
->add('comparisonName', 'text')
->setAttribute('validation_groups', array('delete'))
->getForm()
;
2: Add a public property comparisonName into your entity. (or use a proxy object), that will be mapped to the corresponding form field above.
3: Define a class level, callback validator constraint to compare both values:
/**
* #Assert\Callback(methods={"isComparisonNameValid"}, groups={"delete"})
*/
class Entity
{
public $comparisonName;
public $name;
public function isComparisonNameValid(ExecutionContext $context)
{
if ($this->name !== $this->comparisonName) {
$propertyPath = $context->getPropertyPath() . '.comparisonName';
$context->addViolationAtPath(
$propertyPath,
'Invalid delete name', array(), null
);
}
}
}
4: Display your form in your view:
<form action="{{ path('entity_delete', {'id': entity.id }) }}">
{{ form_rest(deleteForm) }}
<input type="hidden" name="_method value="DELETE" />
<input type="submit" value="delete" />
</form>
5: To verify that the delete query is valid, use this in your controller:
$form = $this->createDeleteForm($object);
$request = $this->getRequest();
$form->bindRequest($request);
if ($form->isValid()) {
$this->removeObject($object);
$this->getSession()->setFlash('success',
$this->getDeleteFlashMessage($object)
);
}
return $this->redirect($this->getListRoute());

Resources