Laravel wrong method - laravel

Laravel basics:
I have the following routes:
Route::group(['prefix' => 'pps', 'as' => 'pps.', 'middleware' => ['auth']], function (){
Route::get('/index', 'PPS\PPSController#index')->name('index');
/**
* Templates
*/
Route::group(['prefix' => 'templates', 'as' => 'templates.', 'middleware' => ['auth']], function (){
Route::get('/', 'PPS\Template\TemplateController#index')->name('index');
/**
* Sequence group
*/
Route::group(['prefix' => 'sequenceGroup', 'as' => 'sequenceGroup.', 'middleware' => ['auth']], function (){
Route::get('/', 'PPS\Template\SequenceGroupController#index')->name('index');
Route::get('/create', 'PPS\Template\SequenceGroupController#create')->name('create');
Route::post('/store', 'PPS\Template\SequenceGroupController#store')->name('store');
Route::get('/edit/{sequenceGroup}', 'PPS\Template\SequenceGroupController#edit')->name('edit');
Route::put('/update/{sequenceGroup}', 'PPS\Template\SequenceGroupController#update')->name('update');
Route::delete('/delete/{sequenceGroup}', 'PPS\Template\SequenceGroupController#delete')->name('delete');
});
/**
* Sequence template
*/
Route::group(['prefix' => 'sequenceTemplates', 'as' => 'sequenceTemplates.', 'middleware' => ['auth']], function (){
Route::get('/{sequenceGroup}', 'PPS\Template\SequenceTemplateController#index')->name('index');
Route::get('/create/{sequenceGroup}', 'PPS\Template\SequenceTemplateController#create')->name('create');
Route::post('/store', 'PPS\Template\SequenceTemplateController#store')->name('store');
Route::get('/edit/{sequenceTemplate}', 'PPS\Template\SequenceTemplateController#edit')->name('edit');
Route::put('/update/{sequenceTemplate}', 'PPS\Template\SequenceTemplateController#update')->name('update');
Route::delete('/delete/{sequenceTemplate}', 'PPS\Template\SequenceTemplateController#delete')->name('delete');
});
});
});
When i update the sequence group, everything works well.
But when i will update the sequence template, laravel goes allways to edit method and not to the update method.
Here my form:
<form action="{{ route('pps.templates.sequenceTemplates.update', $sequenceTemplate->id) }}" method="post">
{{ csrf_field() }}
{{ method_field('put') }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label for="name" class="control-label">#lang('pps.name')</label>
<input type="text" name="name" id="name" class="form-control" value="{{ old('name', $sequenceTemplate->name) }}">
#if ($errors->has('name'))
<span class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('description') ? ' has-error' : '' }}">
<label for="description" class="control-label">#lang('pps.description')</label>
<input type="text" name="description" id="description" class="form-control" value="{{ old('description', $sequenceTemplate->description) }}">
#if ($errors->has('description'))
<span class="help-block">
<strong>{{ $errors->first('description') }}</strong>
</span>
#endif
</div>
<button type="submit" class="btn btn-primary">#lang('pps.save')</button>
</form>
The controller:
public function edit(SequenceTemplate $sequenceTemplate)
{
return view('pps.template.sequenceTemplate.edit', compact('sequenceTemplate'));
}
public function update(UpdateSequenceTemplateRequest $request, SequenceTemplate $sequenceTemplate)
{
$sequenceTemplate->update($request->except('_token', '_method'));
return redirect()->route('pps.templates.sequenceTemplate.index')->withSuccess(__('sequenceTemplateUpdated'));
}
The request:
<?php
namespace App\Http\Requests\PPS\Template;
use Illuminate\Foundation\Http\FormRequest;
class UpdateSequenceTemplateRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'sequence_group_id' => 'required|integer',
'name' => 'required|string|min:3',
];
}
}
What is wrong? i do not find the bug.

When you fill the form and press submit button, Laravel validates the data and redirects you back because there is no sequence_group_id in the form and the field is required:
'sequence_group_id' => 'required|integer',
And you don't see any error message because you're not trying to display it for sequence_group_id. To test it put this to the top of the form:
Errors: {{ dump($errors->all()) }}
And try to submit the form.

Related

laravel 8 Sorry! You have entered invalid credentials

I am using a custom Authentication in Laravel 8 and whenever I try to Enter a valid email/password am getting this error: Sorry! You have entered invalid credentials.
here is my code:
1#Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Session;
use App\Models\User;
use Hash;
use Validator;
class AuthController extends Controller
{
/**
* Write code on Method
*
* #return response()
*/
public function index()
{
return view('auth.login');
}
/**
* Write code on Method
*
* #return response()
*/
public function registration()
{
return view('auth.register');
}
/**
* Write code on Method
*
* #return response()
*/
public function postLogin(Request $request)
{
$request->validate([
'email' => 'required',
'password' => 'required',
]);
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard')
->withSuccess('You have Successfully logged in');
}
return redirect("login")->withSuccess('Sorry! You have entered invalid credentials');
}
/**
* Write code on Method
*
* #return response()
*/
public function postRegistration(Request $request)
{
$request->validate([
'name' => 'required',
'username' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$data = $request->all();
$check = $this->create($data);
return redirect("login")->withSuccess('Great! please login.');
}
/**
* Write code on Method
*
* #return response()
*/
public function dashboard()
{
if(Auth::check()){
return view('dashboard');
}
return redirect("login")->withSuccess('Opps! You do not have access');
}
/**
* Write code on Method
*
* #return response()
*/
public function create(array $data)
{
return User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password'])
]);
}
/**
* Write code on Method
*
* #return response()
*/
public function logout() {
Session::flush();
Auth::logout();
return Redirect('login');
}
}
2#Login.blade.php:
#extends('layouts.layout')
#section('content')
<div class="login-form">
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Login</div>
<div class="card-body">
#if (Session::get('success'))
<div class="alert alert-success" role="alert">
{{ Session::get('success') }}
</div>
#endif
<form action="{{ route('login.post') }}" method="POST">
#csrf
<div class="form-group row">
<label for="email_address" class="col-md-4 col-form-label text-md-right">Email Address</label>
<div class="col-md-6">
<input type="text" id="email_address" class="form-control" name="email" required />
#if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="password" class="col-md-4 col-form-label text-md-right">Password</label>
<div class="col-md-6">
<input type="password" id="password" class="form-control" name="password" required />
#if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
</div>
<div class="col-md-6 offset-md-4">
<button type="submit" class="btn btn-primary">
Login
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
For registration it's working fine, the only problem is in Login form. Hope you can help.
First step: check your user model extends from Authenticable that main user model uses,
Second step:use bcrypt instead of Hash::make,
If solutions doesnt work send your model and config/auth.php for better answer

Route is not defined after successful log in

little bit stuck with redirecting to other page after successful login for quite a long time. I believe that my understanding about sanctum auth is a bottleneck for this issue( Or maybe I am wrong ). However, after reading the docs still couldn't find the answer to my issue. Situation: I have declared few public routes and one private. I have created a user in my database and whenever I try successfully to log in it does not redirect to other page, and my credentials are 110% correct, but anyway after submit it only displays:
Symfony\Component\Routing\Exception\RouteNotFoundException
Route [/dashboard] not defined.
However, I have that route, it's protected but after sign in I assign it. Maybe I am doing in a wrong way?
welcome.blade:
#section('content')
<div class="container-fluid">
<div class="container">
<div class="form-group">
#if ($errors->any())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
<form action="{{action('App\Http\Controllers\AuthController#login')}}" method="POST">
#csrf
<input type="text" class="form-control" placeholder="Email address" name="username" required>
<input type="password" class="form-control" placeholder="Password" name="password" required>
<div class="login-btn">
<button type="submit" class="btn btn-success">Sign in</button>
</div>
</form>
</div>
</div>
</div>
#endsection
AuthController:
public function login(Request $request)
{
$fields = $request->validate([
'username' => 'required',
'password' => 'required',
]);
$user = User::where('username', $fields['username'])->first();
if (!$user || !Hash::check($fields['password'], $user->password)) {
return Redirect::back()->withInput()->withErrors('Incorrect username or password');
} else {
$token = $user->createToken($request->username);
return redirect()->route('/dashboard')->with('token', $token);
}
}
web.php :
// Private routing
Route::group(['middleware' => ['auth:sanctum']], function () {
// Agents dashboard
Route::get('/dashboard', function () {
return view('dashboard.main');
})->name('dashboard');
});
// Public routing
Route::get('/', function () {
return view('welcome');
});
Route::post('/login', [AuthController::class, 'login'])->name('login');
Dashboard -> main:
#extends('layouts.app')
#section('content')
<h1>Private</h1>
#endsection
change ->route('/dashboard') to ->route('dashboard'). This value references the name value on a route. eg:
Route::get('/dashboard', function () {
return view('dashboard.main');
})->name('dashboard');

How to use the same form for add and edit in laravel

I'm new to laravel,i want to use the same form for add and edit.I created an form and form insertion is ok but i need to use the same form edit based on the id selected.When click the edit icon i want to direct the same page displaying the contents to edit.So give me idea for implementing this.
<form method="POST" action="/categoryinsert">
<input type = "hidden" name = "_token" value = "<?php echo csrf_token(); ?>">
<div class="card-body">
<div class="form-group">
<div class="col-md-4">
<label for="exampleInputEmail1">Category</label>
<input type="text" class="form-control" name="category" id="category" placeholder="Enter Category">
</div>
</div>
<div class="card-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
// To create a new user in controller
public function create()
{
// user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate');
}
// To update an existing user
public function edit($id)
{
$user = User::find($id);
// user/createOrUpdate.blade.php view
return View::make('user.createOrUpdate')->with('user', $user);
}
Add/edit in view with the help of user model
#if(isset($user))
{{ Form::model($user, ['route' => ['updateroute', $user->id], 'method' => 'patch']) }}
#else
{{ Form::open(['route' => 'createroute']) }}
#endif
{{ Form::text('fieldname1', Input::old('fieldname1')) }}
{{ Form::text('fieldname2', Input::old('fieldname2')) }}
{{ Form::submit('Save', ['name' => 'submit']) }}
{{ Form::close() }}
// To create a new user in controller
public function create()
{
// user/createOrUpdate.blade.php view
return view('user.createOrUpdate')->with([
'view_type' => 'create',
]);
}
// To update an existing user
public function edit($id)
{
$user = User::find($id);
// user/createOrUpdate.blade.php view
return view('user.createOrUpdate')->with([
'view_type' => 'edit',
'user' => $user
]);
}
<form action="{{ ( $view_type == 'edit' ? route('example', $id) : route('control.mentors.store')) }}" role="form" method="post" name="frmDetail">

Validation errors are not output and fields with previous Form data are not returned

Laravel 5.2
view where the form of sending data ('blade'):
#if( count($errors) > 0 )
<div class="alert alert-danger">
<ul>
#foreach( $errors->all() as $error ) <li>{{ $error }}</li> #endforeach
</ul>
</div>
#endif
<form method="POST" action="{{ route('contact') }}"> <!-- <?//='/contact');?> Or <?//=route('contact');?> -->
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email address:</label>
<input type="email" class="form-control" id="email" name="email" value="{{ old('email') }}" placeholder="Enter E-mail">
</div>
<div class="form-group">
<label for="site">Site:</label>
<input type="text" class="form-control" id="site" name="site" value="{{ old('site') }}" placeholder="Enter Site">
</div>
<div class="form-group">
<label for="text_area">Text:</label>
<textarea class="form-control" id="text_area" name="text_area" rows="3" placeholder="Some text....."> {{ old('text_area') }} </textarea>
</div>
<div class="checkbox">
<label><input type="checkbox" name="checkbox"> Remember me</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div> <!--/class="col-"-->
</div> <!--/class="row"-->
ContactController.php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class ContactController extends Controller {
public function show( Request $request, $prm=false ){
$my_array = ['title1'=>'This variable `$title1` content', 'title2'=>'This variable `$title2` content', 'title3'=>'This variable `$title3` content']; //массив
$my_array2 = ['one'=>array('param1'=>'This variable `param1` content', 'param2'=>'This variable `param2` content', 'param3'=>'This variable `param3` content'),
'two'=>array('param4'=>'This variabl e `param4` content', 'param5'=>'This variable `param5` content', 'param6'=>'This variable `param6` content')
];
$my_array3 = array(
'title'=>'Contact',
'data'=>[ 'one'=>'list 1',
'two'=>'list 2',
'three'=>'list 3',
'four'=>'list 4',
'five'=>'list 5',
],
'dataI'=>['list-1','list-2','list-3','list-4','list-6','list-6'],
'bvar'=>true,
'script'=>"<script>alert('Hello! ++')</script>"
);
/** VALIDATION on Request */
if( $request->isMethod('post') ) {
$rules = [
'name' => 'required|max:10',
'email' => 'required|email',
//'site'=>'required',
//'text_area'=>'required',
];
$messages = [
'required' => 'The :attribute field is required.',
];
$this->validate($request, $rules, $messages);
dump( $request->all() );
dump( $request->session()->all() );
}
if( view()->exists('default.contact') ){
return view('default.contact')
->withMydata($my_array2)
->withMydata2($my_array)
->withMydata3($my_array3);
}
else { abort(404); }
}
}
/app/Http/Kernel.php
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* #var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
];
How can I see that validation fulfills and its rules are in effect,
But I do not see the display of validation errors when it is not passed and the data in the input fields when the Form is filled when redirecting back.
Let me show you my method which also uses validation on Laravel 5.2 and find out what the difference you have with this code:
The Controller which handles the request:
$validator = \Validator::make($request->all(), [
'data1' => 'required',
'data2' => 'required|in:bla1,bla2,bla3',
'data3' => 'required|array',
'data3.*' => 'required|json',
'data4' => 'required_if:data2,bla2',
]);
if ($validator->fails()) {
$request->flash();
return \Response::make(\View::make('theform')
->withErrors($validator)
->withInput($request->all())
->render()
, 406);
}
The form which contains the form which has been submitted and redrawn with error logs, named 'theform':
<input type="text" class="form-control" name="trip_name" id="trip_name"
placeholder="Gezi ismi" value="{{ old('trip_name') }}">
#if ($errors->has('trip_name'))
<span class="help-block">
<strong>{{ $errors->first('trip_name') }}</strong>
</span>
#endif
This is one way to show it. You can also view it your way as:
#if( count($errors) > 0 )
<div class="alert alert-danger">
<ul>
#foreach( $errors->all() as $error )
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Well, the problem did not stop there ))
I create the validation through my own class Request and divide routes for GET and POST and defined separate methods for them in my Controller.
1. app/Http/routes.php
Route::get('/contact_form/{prm?}', ['uses'=>'Admin\ContactformController#show_form_get'])->name('contact_form');
Route::post('/contact_form', ['uses'=>'Admin\ContactformController#show_form_post']);
2. app/Http/Requests/ContactRequest.php - my custom Request class with validation rules:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class ContactRequest extends Request
{
public function authorize()
{
return true; //false
}
public function rules()
{
return [
'name' => 'required|max:10',
//'name' => 'exists:users,name',
'email' => 'required|email',
'site'=>'required',
];
}
} //__/class ContactRequest
3. app/Http/Requests/ContactRequest.php - my Controller with POST and GET handling:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\ContactRequest; //custom Request class with validation rules
use App\Http\Controllers\Controller;
use \Illuminate\Support\Facades\Validator;
class ContactformController extends Controller {
public $show_controller_method = array(__METHOD__);
/** Method handler http-request with GET
*/
public function show_form_get( ){
$this->show_controller_method[] = 'showform()';
if( view()->exists('default.contact_form') ){
return view('default.contact_form')->withInfoMethodController($this->show_controller_method);
}
else { abort(404); }
} //__/public function show_form_get()
/** Method handler http-request with POST
*/
public function show_form_post( ContactRequest $request ){
if( $request->isMethod('post') ):
dump( $request->all() );
endif;
}
3. The view remained the same and there is a return of data "old inputs":
value="{{ old('name') }}" value="{{ old('email') }}" and so on...
and errors of validation if they exist:
#if( count($errors) > 0 )
<div class="alert alert-danger">
<ul>
#foreach( $errors->all() as $error ) <li>{{ $error }}</li> #endforeach
</ul>
</div>
#endif
Now the validation works (if it passes successfully - I see a dump() the POST.
If the validation falls, then a redirect occurs, but there are no validation errors and there are no old inputs.
Tell me please what I'm doing is not right?

Laravel - If has errors on validation, insert class in the specifics inputs

I'm totally noob in PHP, but my question is, after the validation which has errors for specific inputs, how can I insert a class in the specific input?
Example, if i have this error in the validation: "The email field is required."
How can i insert a specific class in the email input?
Login routes:
Route::group(['prefix' => 'admin'], function () {
Route::get('/', 'Admin\AdminController#index');
Route::get('login', 'Admin\AuthController#getLogin');
Route::post('login', 'Admin\AuthController#postLogin');
Route::get('logout', 'Admin\AuthController#getLogout');
});
AdminController:
class AdminController extends AdminBaseController
{
public function index()
{
if(Auth::user()){
return view('admin/pages/admin/index');
}
return view('admin/pages/login/index');
}
}
AuthController:
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
private $redirectTo = '/admin';
public $loginPath = '/admin';
public function __construct()
{
$this->middleware('guest', ['except' => 'getLogout']);
}
public function getLogin()
{
if(Auth::user()){
return redirect('/admin');
}
return view('admin/pages/login/index');
}
public function postLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
}
}
My blade form:
<form class="s-form" role="form" method="POST" action="/admin/login">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="s-form-item text">
<input type="text" name="email" value="{{ old('email') }}" placeholder="Email">
</div>
<div class="s-form-item text">
<input type="password" name="password" value="{{ old('password') }}" placeholder="Senha">
</div>
<div class="s-form-item">
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif
</div>
<div class="s-form-item s-btn-group s-btns-right">
<input class="s-btn" type="submit" value="Entrar">
</div>
</form>
You can pass an argument to the has method to specify the specific key.
For example, for your email input...
<input class="#if($errors->has('email')) some-class #endif" ... >
I left out the rest of the input field for brevity. It basically checks if an error for the email input exists. If so, 'some-class' is outputted. Otherwise, it skips over it.
Edit: To answer the question on how you can customize where to output your error messages, you can use the get or first methods in conjunction with the has method. For example...
#if ($errors->has('email'))
#foreach ($errors->get('email') as $error)
<p>{{ $error }}</p>
#endforeach
#endif
The has method has already been explained. The get method retrieves the validation errors. Because there can be more than one validation error, you must loop through it and output it.
In the next example, I use first. This method just outputs the first error message so there is no need to loop through it.
#if ($errors->has('email'))
<p>{{ $errors->first('email') }}</p>
#endif

Resources