methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php laravel 5.0 - laravel

I want to login as I submit the form but I am getting an error.
The form code is as follows:
{!! Form::open() !!}
{{ $errors->first("parentPassword") }}<br />
<div>
<legend>Parent</legend>
Email<br>
<input type="email" id="email" name="parentEmail" required>
<br>
Password<br>
<input type="password" name="parentPassword">
<br><br>
</div>
{!!Form::submit('Submit',array('class' => 'btn btn-outline btn-primary')) !!} </fieldset>
{!! Form::close() !!}
The controller code is as follows:
App\Http\Controllers;
use Illuminate\Support\Facades\Redirect;
class loka extends Controller
{
public function login()
{
if ($this->isPostRequest()) {
$validator = $this->getLoginValidator();
if ($validator->passes()) {
$credentials = $this->getLoginCredentials();
if (Auth::attempt($credentials)) {
return redirect()->intended('/');
}
return Redirect::back()->withErrors([
"parentPassword" => ["Credentials invalid."]
]);
} else {
return Redirect::back()
->withInput()
->withErrors($validator);
}
}
return view("signup.index");
}
protected function isPostRequest()
{
// return Request::isMethod('post');
}
protected function getLoginValidator()
{
return Validator::make(Request::all(), [
"parentEmail" => "required",
"parentPassword" => "required"
]);
}
protected function getLoginCredentials()
{
return [
"parentEmail" => Request::input("parentEmail"),
"parentPassword" => Request::input("parentPassword")
];
}
}
The route is as follows:
Route::patch("/index", [
"as" => "login/index",
"uses" => "loka#login"
]);

Related

My laravel livewire create form keeps giving me errors

LONG POST WARNING
why isn't my form to create a new user not working? im using laravel 9 and livewire. This is my code:
this is the button from where i show the model to create a form:
<div class="py-4 space-y-4">
<div class="flex justify-between px-2">
<div class="w-1/4">
<x-jet-input placeholder="search will go here"/>
</div>
<div>
<x-jet-button wire:click="create">New Skill</x-jet-button>
</div>
</div>
</div>
This is the model that shows the form. this model is also used to edit a skill as per Caleb the livewire creator:
<form wire:submit.prevent="save">
<x-jet-dialog-modal wire:model.defer="showEditModal">
<x-slot name="title">Edit Skill</x-slot>
<x-slot name="content">
<div class="col-span-6 sm:col-span-4">
<x-jet-label for="name" value="{{ __('Skill name') }}" />
<select wire:model="editing.name"
id="name"
type="text"
class="mt-1 block w-full border-gray-300
focus:border-indigo-300 focus:ring
focus:ring-indigo-200 focus:ring-opacity-50
rounded-md shadow-sm">
#foreach(\App\Models\Skill::LANGUAGES as $value => $label)
<option value="{{ $value }}">{{ $label }}</option>
#endforeach
</select>
<x-jet-input-error for="editing.name" class="mt-2" />
<x-jet-label for="years" value="{{ __('Years of experience') }}" class="mt-4"/>
<x-jet-input wire:model="editing.years" id="years" type="number"
min="{{\App\Models\Skill::MIN_YEARS_OF_EXPERIENCE}}"
max="{{\App\Models\Skill::MAX_YEARS_OF_EXPERIENCE}}"
class="mt-1 block w-full"
placeholder="Years of experience"/>
<x-jet-input-error for="editing.years" class="mt-2" />
</div>
</x-slot>
<x-slot name="footer">
<x-jet-secondary-button wire:click="$set('showEditModal', false)" class="mr-2">Cancel</x-jet-secondary-button>
<x-jet-button type="submit">Save</x-jet-button>
</x-slot>
</x-jet-dialog-modal>
</form>
And this is my livewire component:
<?php
namespace App\Http\Livewire;
use App\Models\Skill;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class Skills extends Component
{
public $name ='';
public $showEditModal = false;
public Skill $editing;
public function rules()
{
return [
'editing.name' => 'required|in:'.collect(Skill::LANGUAGES)->keys()->implode(','),
'editing.years' => 'required|numeric|between:' . Skill::MIN_YEARS_OF_EXPERIENCE . ',' . Skill::MAX_YEARS_OF_EXPERIENCE,
];
}
public function render()
{
return view('livewire.skills', [
'skills' => Skill::where('user_id', auth()->id())->get(),
]);
}
public function mount(){
$this->editing = $this->makeBlankSkill();
}
public function makeBlankSkill(){
return Skill::make([
'name' => 'javascript',
'user_id' => auth()->user()->id,
]);
}
public function create(){
if ($this->editing->getKey()) $this->editing = $this->makeBlankSkill();
$this->showEditModal = true;
}
public function edit(Skill $skill) {
if ($this->editing->isNot($skill)) $this->editing = $skill;
$this->showEditModal = true;
}
public function save()
{
$this->validate();
$this->editing->save();
$this->showEditModal = false;
}
}
I keep getting SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value and i dont know why.
This is my modal:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Skill extends Model
{
use HasFactory;
const DEFAULT_OPTION = 'Please select a skill';
const LANGUAGES = [
'javascript' => 'JavaScript',
'php' => 'PHP',
'python' => 'Python',
'java' => 'Java',
'c#' => 'C#',
'c++' => 'C++',
'ruby' => 'Ruby',
'swift' => 'Swift',
'typescript' => 'TypeScript',
'rust' => 'Rust',
'go' => 'Go',
'kotlin' => 'Kotlin',
'scala' => 'Scala',
'dart' => 'Dart',
'r' => 'R',
'perl' => 'Perl',
'elixir' => 'Elixir',
'clojure' => 'Clojure',
'haskell' => 'Haskell',
'erlang' => 'Erlang',
'lisp' => 'Lisp',
'sql' => 'SQL',
'bash' => 'Bash',
'laravel' => 'Laravel',
'symfony' => 'Symfony',
'codeigniter' => 'CodeIgniter',
'yii' => 'Yii',
'zend' => 'Zend',
'cakephp' => 'CakePHP',
'fuelphp' => 'FuelPHP',
'slim' => 'Slim',
'lumen' => 'Lumen',
'phalcon' => 'Phalcon',
'silex' => 'Silex',
'express' => 'Express',
'koa' => 'Koa',
'hapi' => 'Hapi',
'meteor' => 'Meteor',
'angular' => 'Angular',
'ember' => 'Ember',
'react' => 'React',
'vue' => 'Vue',
'backbone' => 'Backbone',
'd3' => 'D3',
'threejs' => 'Three.js',
];
const MIN_YEARS_OF_EXPERIENCE = 1;
const MAX_YEARS_OF_EXPERIENCE = 50;
protected $fillable = [
'name', 'user_id', 'years'
];
public function user()
{
return $this->belongsTo(User::class);
}
}
Any help is greatly appriceated
I've done all there is to do.At least i hope. I've added the
$illable
array ive set the
'user_id' => auth()->user()->id,
Not sure what else im missing
public function save()
{
$this->validate();
$user = auth()->user();
$this->editing->user_id = $user->id;
$this->editing->save();
$this->showEditModal = false;
}
This was the answer for me
If user_id is null when creating a new Skill, this means there is no authenticated user. You can simply check by doing dd(auth()->id()). If you're logged in, this will return the primary key for your authentication model. If this is empty, you're simply not authenticated, and so you must first log in.
In the case your user_id is actually set, but it isn't arriving in your database upon saving, you'll have to check if the property user_id is correctly set on the Skill model's protected $fillable property.
If you dd($this->editing) right after mount, you can check the attributes of the model, and if the user_id is set, you know the error happens when saving to the database.
As it turns out, Livewire won't hydrate newly set properties on models. This is because Livewire "rehydrates" the models by simply re-fetching them from the database. This can be solved defining a rules property as shown here, directly relating to the model properties. This would ensure Livewire keeps the state of the updated properties.

delete if password is correct

i need to create a condition that clears the record but with a password.
if the password is correct execute the delete();
controller:
public function eliminar($id){
$registros = \App\Models\Registro::findOrFail($id);
$registros->delete();
return redirect('sistema')->with('mensaje', 'Registro Borrado con exito');
}
public function borrar($id){
// return $request->all();
$data = [
'category_name' => 'datatable',
'page_name' => 'multiple_tables',
'has_scrollspy' => 0,
'scrollspy_offset' => '',
'fechax' => Carbon::now(),
'borrar' => \App\Models\Registro::findOrFail($id),
'password' => 'PASSCODE',
];
return view('borrar')->with($data);
}
blade.php:
<h1>Do you want to delete the record?</h1>
<form action="{{ route('eliminar', $borrar) }}" class="d-inline" method="POST">
#method('DELETE')
#csrf
<button type="submit" class="btn btn-danger btn-sm">DELETE</button>
<div class="form-group col-md-6">
<label for="telefono">Password</label>
<input name="password" type="password" class="form-control" id="telefono" required>
</div>
</form>
the password is obtained statically
How can I make it delete without the password is identical?
help please
If the password is saved statically, inside in a variable, the following should do the job for you.
routes/web.php
Route::delete('/path/here', 'SomeController#destroy');
SomeController.php
public function destroy($id)
{
$model = YourModel::find($id);
if (! $model) {
session()->flash('error_message', 'Model not found with the given id: ', . $id);
return back();
}
// $password is the password that you have saved somewhere
if (request()->password_field_value == $password) {
$model->delete();
session()->flash('success_message', 'Model deleted successfully.');
return back();
}
session()->flash('error_message', 'Invalid password. Try again');
return back();
}

How to validate Dynamic input in vuejs / Laravel

I'm catching errors via interceptors and a Toast for UI. Usually the error is caught by the interceptor and displayed via the toast for one-time inputs, i'm trying to catch errors for an uncertain number of inputs. So far looping through the input array and setting rules does not work.
Component.vue
<template>
<div>
<div class="form-group" v-for="(input,k) in inputs" :key="k">
<input type="text" id="name" placeholder="Name" v-model="input.name" />
<span>
<i class="fas fa-minus" #click="remove(k)" v-show="k || ( !k && inputs.length > 1)"></i>
<i class="fas fa-plus" #click="add(k)" v-show="k == inputs.length-1"></i>
</span>
</div>
<button #click="addName">Create</button>
</div>
</template>
<script>
export default {
data() {
return {
inputs: [{name: ''}]
}
},
methods: {
add(index) {
this.inputs.push({ name: ''});
console.log( this.inputs);
},
remove(index) {
this.inputs.splice(index, 1);
},
addName() {
axios.post('/user', {userinputs:this.inputs}).then(response => {})
.catch(error => {
console.log(error);
});
}
}
}
</script>
Controller:
public function store(Request $request)
{
$rules = [
'userinputs' => 'required|max:255',
];
foreach ($request->input('userinputs') as $key => $my_object_in_array) {
$rules[$my_object_in_array['name']] = 'required|max:10';
}
return $rules;
}
I hope this is what you wanted to achieve.
public function store(Request $request)
{
$rules = [
'userinputs.*.name' => 'required|max:255',
];
$validator = \Illuminate\Support\Facades\Validator::make($request->all(), $rules);
if ($validator->fails()) {
//Return the errors as JSON
return response()->json(['success' => 'false', 'errors' => $validator->errors()], 400);
}
//Do something
return ['success' => 'true'];
}

Undefined Index:email Error In Laravel 5.6

I want to make login functionality for my website. But unfortunately it is giving undefined Index:email in my AdminController:
public function login(Request $request)
{
if($request->isMethod('post'))
{
$data = $request->input();
if (Auth::attempt(['email' => $data['email'], 'password' => $data['password'],'admin' => '1'])) {
echo "Success";
//console.log("Successfull");
die;
}
else
{
echo "Failed";
//console.log("Failed");
die;
}
}
return view('admin.admin_login');
}
In Blade:
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text bg-success text-white" id="basic-addon1"><i class="ti-user"></i></span>
</div>
<input type="email" name="email" class="form-control form-control-lg" placeholder="Email" aria-label="Email" aria-describedby="basic-addon1" required="">
</div>
change $data['email'] to $request->email.Because $request contain object not an array
You can do the following
public function login(Request $request)
{
if($request->isMethod('post'))
{
if (Auth::attempt(['email' =>$request->email, 'password' => $request->password,'admin' => '1'])) {
echo "Success";
//console.log("Successfull");
die;
}
else
{
echo "Failed";
//console.log("Failed");
die;
}
}
return view('admin.admin_login');
}
even i dont see password field in your blade template

After redirection, Try to retrieve session but session auto cleared In laravel 5.4

After redirection,I try to retrieve session in home() using 'dd(session('key'))' but session auto cleared and got null value In laravel 5.4 and also i didn't found any error or warning message.
Before redirection session set and get are working.
I have below code:
LoginController.php
<?php
namespace App\Http\Controllers\admin;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\employers;
use App\Model\admin;
use Session;
use DB;
use Validator;
class LoginController extends Controller
{
public function index(){
$users = employers::all();
return view('user_view',['users'=>$users]);
}
public function insert_record(){
$users = new employers;
$users->userFname = 'Nikunj';
$users->userLname = 'Makwana';
$users->gender = 'Male';
$users->created_at = time();
$users->updated_at = time();
$users->save();
}
public function login(){
return view('admin/login',['errors'=>array()]);
}
public function home(){
dd(session('key'));
}
public function checklogin(Request $request){
$validator = Validator::make($request->all(), [
'username' => 'required|email',
'password' => 'required',
]);
if($validator->fails()) {
$errors = $validator->errors();
$validation_errors['username'] = $errors->first('username');
$validation_errors['password'] = $errors->first('password');
return view('admin/login',['errors'=>$validation_errors]);
}
$input = $request->all();
$username = $input['username'];
$password = $input['password'];
$admin_login = admin::where('username', $username)
->where('password', $password)
->count();
if($admin_login){
session(['key' => 'value']);
return redirect('admin_home');
}
else
{
return redirect('admin');
}
}
}
Views/admin/login.blade.php
<form method="post" action="{{ 'admin_login' }}">
{{ csrf_field() }}
<fieldset>
<label>
<span class="block input-icon input-icon-right">
<input type="text" name="username" class="span12" placeholder="Username" />
<i class="icon-user"></i>
</span>
</label>
<label>
<span class="block input-icon input-icon-right">
<input type="password" name="password" class="span12" placeholder="Password" />
<i class="icon-lock"></i>
</span>
</label>
<div class="space"></div>
<div class="clearfix">
<label class="inline">
<input type="checkbox" />
<span class="lbl"> Remember Me</span>
</label>
<button type="submit" class="width-35 pull-right btn btn-small btn-primary">
<i class="icon-key"></i>
Login
</button>
</div>
<div class="space-4"></div>
</fieldset>
</form>
Route/Web.php
<?php
Route::get('/', function () {
return view('welcome');
});
//For database Query
Route::get('/employers','UserController#index');
Route::get('/add_employer','UserController#add_employer');
Route::match(['get','post'],'/insert_employer /','UserController#insert_record');
// For Admin
Route::get('/admin','admin\LoginController#login');
Route::get('/admin_logout','admin\LoginController#logout');
Route::get('/admin_home','admin\LoginController#home');
Route::match(['get','post'],'/admin_login/','admin\LoginController#checklogin');
Kernel.php
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
protected $middleware = [
'\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class',
'\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class',
'\App\Http\Middleware\TrimStrings::class',
'\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class',
];
protected $middlewareGroups = [
'web' => [
'\App\Http\Middleware\EncryptCookies::class',
'\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class',
'\Illuminate\Session\Middleware\StartSession::class',
'\Illuminate\Session\Middleware\AuthenticateSession::class',
'\Illuminate\View\Middleware\ShareErrorsFromSession::class',
//'\App\Http\Middleware\VerifyCsrfToken::class',
'\Illuminate\Routing\Middleware\SubstituteBindings::class',
],
'api' => [
'throttle:60,1',
'bindings',
],
];
protected $routeMiddleware = [
'auth' => '\Illuminate\Auth\Middleware\Authenticate::class',
'auth.basic' => '\Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class',
'bindings' => '\Illuminate\Routing\Middleware\SubstituteBindings::class',
'can' => '\Illuminate\Auth\Middleware\Authorize::class',
'guest' => '\App\Http\Middleware\RedirectIfAuthenticated::class',
'throttle' => '\Illuminate\Routing\Middleware\ThrottleRequests::class',
'Role' => '\App\Http\Middleware\RoleMiddleware::class',
//'csrf' => 'App\Http\Middleware\VerifyCsrfToken'// add it as a middleware route
];
}

Resources