Passing submit form to controller in laravel 7 - php

I have a submit form which I want to send to my RegisterController and I get this error
""Too few arguments to function App\Http\Controllers\Auth\RegisterController::create(), 0 passed and exactly 1 expected""
The create method demands an array.How to convert my request ot an array?
the form:
<form method="POST" action="{{ route('posting') }}">
#csrf....and so on
the routes:
Route::get('administration/register', function () {
return view('vregister');
})->name('registration');
Route::post('/insert','Auth\RegisterController#create')->name('posting');
method of RegisterController.php
protected function create(array $data)
{
$user= User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$role=Role::select('id')->where('name','Support')->first(); //??
$user->roles()->attach($role);
return $user;
}

You are using wrong instance in your create method. When using forms, you should use Request class to actually send form data to your controller. The way you have it, no data is being sent to create() method, hence the error. Edit your create() method to this:
protected function create(Request $data)
And import Request class at the top:
use Illuminate\Http\Request;
Read more at the official documentation
.
EDIT:
To redirect to a specific page after saving the data, change your return statement to this:
return redirect()->back();
This will return you back to the previous page. You can also add any route here, that you wish to redirect to:
return redirect()->rote('route.name');

Related

Login with one parameter

I want to make a login in Laravel that receives only one parameter, i.e. has a simple form that receives one input, and based on that input, the user is authenticated. If user is admin, it will redirect to /adminpage, else if the user is a regular user it redirects to /homepage.
I want to use a custom table, model, and controller. I searched the internet but could not find a solution.
EDIT
I have form like this:
<form action="someroute" method="POST">
<input type="text" name="rf_id">
<input type="submit" value="login">
</form>
My migration is:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('lastname');
$table->string('workid');
$table->boolean('isAdmin')->default(False);
$table->string('rf_id');//
$table->timestamps();
});
Now i need controller that handle this.
So base on rf_id, controller needs to fin user and thec check his role.
I try this but don't work:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class TestController extends Controller
{
public function index(){
return view('singin');
}
public function login(Request $request){
$credentials = $request->only('rf_id');
if(Auth::attempt($credentials)){
//we need to know who is logging in
return $this->filterAndRedirect(Auth::user());
}
return "there is no user with that rfid";
}
private function filterAndRedirect(User $user){
//the function to take care of the routing
if($user->isAdmin){
# return redirect('/homepage');
return "This is admin";
}
else{
# return redirect('/adminpage');
return "This is worker";
}
}
}
Here is how I would do it;
First of all you have to add the table column in your migration file for the user-type and the login parameter.Check below for migration docs
Next is the page where you have the form, I don't know what your parameter is so I'll just call it 'param'. I am assuming you know how to create and submit forms with laravel so I won't put the code here.
Now the interesting part, the controllers:
This is how my user creation in the RegisterController would look;
Note that I'm using the standard laravel auth controllers
public function createStandardUser(Request $request){
//function to add the Standard user
$user = User::create([
'name' => $request['name'],
'email' => $request['email'],
'param' => $request['login-param'],
'user-type' => 'standard'//the user type
]);
Auth::login($user);//Explicitly starts a new session for the user
return redirect('/homepage');
}
If you are gonna have a different form for the Admin registration the function to add the admin user will roughly be the same;
public function createAdminUser(Request $request){
//function to add the Admin user
$user = User::create([
'name' => $request['name'],
'email' => $request['email'],
'param' => $request['login-param'],
'user-type' => 'admin'//the user type
]);
Auth::login($user);//Explicitly starts a new session for the user
return redirect('/adminpage');
}
The last part would be the LoginController where you can use the attempt() function to authenticate the user and start a new session for them using your single parameter.
You will have these functions
public function login(Request $request){
if(Auth::attempt(['login-param' => $request->get('login-param'])){
//we need to know who is logging in
return $this->filterAndRedirect(Auth::user());
}
}
private function filterAndRedirect(User $user){
//the function to take care of the routing
if($user->user-type == 'standard'){
return redirect('/homepage');
}else if($user->user-type == 'admin'){
return redirect('/adminpage');
}
}
The Relevant Documentation:Database Migration Docs, Laravel Authentication Docs
Suggestion:If I were you I would use Roles/Permissions as opposed to using a table row in your DB, I think its more robust. Check out this library it is well documented and gets updated ->Laravel Permission By Spatie
EDIT:This answer assumes you are using the standard User model and Authentication Controllers because thats the whole point of using a framework isn't it?

Call to a member function fails() on array

I have a problem with the laravel validation.
Call to a member function fails() on array
Symfony\Component\Debug\Exception\FatalThrowableError thrown with message "Call to a member function fails() on array"
Stacktrace:
`#0 Symfony\Component\Debug\Exception\FatalThrowableError in
C:\laragon\www\frontine\app\Http\Controllers\authController.php:37
public function postRegister(Request $request)
{
$query = $this->validate($request, [
'user' => 'string|required|unique:users|min:4|max:24',
'email' => 'email|string|required|unique:users',
'pass' => 'string|required|min:8',
'cpass' => 'string|required|min:8|same:pass',
'avatar' => 'image|mimes:jpeg,jpg,png|max:2048',
]);
if ($query->fails())
{
return redirect('/registrar')
->withErrors($query)
->withInput();
}
}
The error is because what the ->validate() method returns an array with the validated data when applied on the Request class. You, on the other hand, are using the ->fails() method, that is used when creating validators manually.
From the documentation:
Manually Creating Validators
If you do not want to use the validate method on the request, you may
create a validator instance manually using the Validator facade. The
make method on the facade generates a new validator instance:
use Validator; // <------
use Illuminate\Http\Request;
class PostController extends Controller
{
public function store(Request $request)
{
$validator = Validator::make($request->all(), [ // <---
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
}
The ->fails() is called in the response of the Validator::make([...]) method that return a Validator instance. This class has the fails() method to be used when you try to handled the error response manually.
On the other hand, if you use the validate() method on the $request object the result will be an array containing the validated data in case the validation passes, or it will handle the error and add the error details to your response to be displayed in your view for example:
public function store(Request $request)
{
$validatedData = $request->validate([
'attribute' => 'your|rules',
]);
// I passed!
}
Laravel will handled the validation error automatically:
As you can see, we pass the desired validation rules into the validate
method. Again, if the validation fails, the proper response will
automatically be generated. If the validation passes, our controller
will continue executing normally.
What this error is telling you is that by doing $query->fails you're calling a method fails() on something (i.e. $query) that's not an object, but an array. As stated in the documentation $this->validate() returns an array of errors.
To me it looks like you've mixed a bit of the example code on validation hooks into your code.
If the validation rules pass, your code will keep executing normally;
however, if validation fails, an exception will be thrown and the
proper error response will automatically be sent back to the user. In
the case of a traditional HTTP request, a redirect response will be
generated, [...]
-Laravel Docs
The following code should do the trick. You then only have to display the errors in your view. You can read all about that, you guessed it, in... the docs.
public function postRegister(Request $request)
{
$query = $request->validate($request, [
'user' => 'string|required|unique:users|min:4|max:24',
'email' => 'email|string|required|unique:users',
'pass' => 'string|required|min:8',
'cpass' => 'string|required|min:8|same:pass',
'avatar' => 'image|mimes:jpeg,jpg,png|max:2048',
]);
}

How to check for required fields in object?

i have example object with fields
name => John
surname => Dow
job => engineer
and output form with placeholders. some required, some not.
what is best practice for check if it requred and show error with null fields?
There are multiple ways actually you can do that inside of controller method or make use of Laravels Request Classes for me I prefer to use Request Classes
look below I will list the two examples
Validate inside the controller's method
public function test(Request $request){
if($request->filled('name){
/*filled will check that name is set on the current
request and not empty*/
//Do your logic here
}
}
Second way is by using the Validator Facade inside your controller
use Validator;
class TestController{
public function test(Request $request){
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
/*continue with your logic here if the request failed on
validator test Laravel will automatically redirect back
with errors*/
}
}
Third way my favorite one personally
you can generate a Request class using this command
php artisan make:request AddBookRequest
that will generate the request class under "app/Http/Requests/AddBookRequest" , inside of any generated request class you will find two methods authorize() and rules()
in the authorized method you have to return truthy or falsy value this will detect if the current user making the request has authorization to fire this request inside of the rules method you do pretty much as you did in the Validator in the second way check the example
public function authorize(){
return true;
}
public function rules(){
return [
'title' => 'required|string',
'author_id' => 'required|integer'
];
}
then simply in your controller you can use the generated request like this
use App\Http\Requests\AddBookRequest;
public function store(AddBookRequest $request){
/* do your logic here since we uses a request class if it fails
then redirect back with errors will be automatically returned*/
}
Hope this helps you can read more about validation at
https://laravel.com/docs/5.6/validation
I think "simple is the best", just through object and check if properties exists
Ref: property_exists
Example:
if (property_exists($object, 'name')) {
//...do something for exists property
} else {
//...else
}

Very Confusing MethodNotAllowedHttpException on a put request laravel

So far all attempts to modify the routing methods have failed.
Been following some documentation on laravel restful controllers and have one set up to do basic editing and adding of items to a database. It was going well till I hit the snag on... well I'm not sure what precisely is triggering the problem, but basically, everything works till I hit submit on the form and then it's Game Over.
Normally I'd be able to diagnose this by checking to see if I'm using the right call, or made a spelling mistake or something. But this is a new request for me, so I can't quite debug where the problem is coming from.
This is the error those who know what to look for. In full here.
MethodNotAllowedHttpException in RouteCollection.php line 218:
My routes are pasted here.
A printout of the routes is here:
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ContactFormRequest;
use App\UserEdit;
use DB;
use App\Http\Requests;
class EditUserController extends Controller
{
public function index()
{
$array = UserEdit::all()->toArray();
return view('UserEntry', compact('array'));
}
public function create()
{
$id = UserEdit::find(715)->toArray();
return view('NewUser', compact('id'));
}
public function store(UserFormRequest $request)
{
//$user = new UserEdit([
// 'name'=>$request->get('First_Name'),
// 'email'=>$request->get('email'),
// 'username'=>$request->get('name')
//]);
//
//$user->save();
//return \Redirect::route('users')->with('message', 'Nice Work.');
}
public function show($id)
{
try {
$array = UserEdit::findorFail($id)->toArray();
return view('UserEdit')->with('array', $array);
} catch(\Exception $e) {
return \Redirect::route('users.index')
->withMessage('This user does not exist');
}
}
public function edit($id)
{
$user = UserEdit::findorFail($id);
return view('EditUser')->with('user',$user);
}
public function update($id, UserFormRequest $request)
{
$user = UserEdit::findorFail($id);
$user->update([
'name' => $request->get('name'),
'email' => $request->get('email')
]);
return \Redirect::route('users.edit', [$user->id])->with('message', 'Details Updated!');
}
public function destroy($id)
{
//
}
}
The Blade is here.
if you have a hard time finding the solution the easiest solution is using
Route::any('users/{user}', 'UserEntryController#update');
this allow you to access this action with any method type
OR
Route::match(array('get', 'put'), 'users/{user}', 'UserEntryController#update');
so you need 2 method which are
get -> view
put -> submit update
you can just indicate which method type you want to be accessible with in this action
i think you are using model in form.try this
{{ Form::open(['method' => 'put', 'route'=>['users.update', $user->id], 'class'=>'form']) }}
As per your route list and route put doesnt taking id so you get method not found exception
PUT users/{user} App\Http\Controllers\EditUserController#update
instead of using resouce just type each route for each method
Route::put('users/{user}', 'EditUserController #update');
It seems like after sorting out the routes, the issue fell to a bad capitalisation. $user->id should have been $user->ID.

Using a CustomRequest for Form Validation in Laravel 5.1 fails?

I've created a custom Request called CustomerRequest that I want to use to validate the form fields when a new customer is created. I cannot get it to work, it appears to be continuing into the store() method even when it should fail.
I have three required fields: givenname, surname, email
Here is my CustomerRequest:
public function rules()
{
return [
'givenname' => 'required|max:3',
'surname' => 'required',
'email' => 'required|unique:customers,email',
];
}
Here is my CustomerController:
use pams\Http\Requests\CustomerRequest;
-----------------------------------------
public function store(CustomerRequest $request, Customer $customer)
{
$request['created_by'] = Auth::user()->id;
$request['modified_by'] = Auth::user()->id;
$customer->create($request->all());
return redirect('customers');
}
When I submit the form using a givenname of "Vince" it should fail because it is greater than 3 characters long, but instead I get this error:
FatalErrorException in CustomerController.php line 52: Cannot use object of type pams\Http\Requests\CustomerRequest as array
Line 52 in the controller is $request['created_by'] = Auth::user()->id;
From what I understand, if the CustomerRequest fails then the user should be redirected back to the customers.create page and not run the code contained in the store() method.
I found the problem.
CustomerRequest had:
use Request;
instead of:
use pams\Http\Requests\Request;
Now the validation passes and fails as expected.
From docs, in Form Request Validation:
All you need to do is type-hint the request on your controller method.
The incoming form request is validated before the controller method is
called, meaning you do not need to clutter your controller with any
validation logic
Solution would be if you use it like so:
CustomerController.php
use Illuminate\Http\Request;
// ...
public function store(CustomerRequest $customerRequest, Customer $customer,Request $request)
{
$request['created_by'] = Auth::user()->id;
$request['modified_by'] = Auth::user()->id;
$customer->create($request->all());
return redirect('customers');
}
So what you want to know is that FormRequest -- which you are extending in your custom request validator CustomerRequest.php -- is a bit different than request that resides in Illuminate\Http namespace.
actually, you may find out why if you run (with your old code) dd($request['created_by'] = Auth::user()->id);. you should get the word forbidden or maybe! an exception telling that it'is not instantiable. (in my case I got forbidden because I've tested it on 5.2 right now).
$request is object, use it like following
use pams\Http\Requests\CustomerRequest;
-----------------------------------------
public function store(CustomerRequest $request, Customer $customer)
{
$inputs = $request->all();
$inputs['created_by'] = Auth::user()->id;
$inputs['modified_by'] = Auth::user()->id;
$customer->create($inputs);
return redirect('customers');
}

Categories