BadMethodCallException Method App\Http\Controllers\UsuarioController::update does not exist - php

I'm new to Laravel (I'm using version 8) and I've been reviewing this error for a long time and I don't know what else to try.
I have a resource controller called ** UserController.php ** and I set the path in ** web.php ** as follows:
Route::resource('usuarios', App\Http\Controllers\UsuarioController::class);
The resource paths are:
The user can enter their profile and modify their fields through this menu option that invokes the edit() method of the controller:
So far everything works very well, but when the user enters to edit in the ** edit.blade.php ** form, and selects the "update" button that calls the method ** update () ** of the controller, it jumps to me the error: BadMethodCallException
Method App\Http\Controllers\UsuarioController::update does not exist.
This is edit.blade.php:
#section('title', 'Mi Perfil')
#section('intro')
#endsection
<br><br>
<style type="text/css">
h5 {text-align: center}
nav.navbar {
background-color: #34495E;
}
</style>
#section('content0')
<div class="container3">
<div class="bShadow3 bShadow-33">
<form method="POST" action="{{route('usuarios.update',[Auth::user()->slug]) }}">
#method('PUT')
#csrf
<br>
<h5>Mi perfil</h5>
<div class="form-group ml-5 mr-5">
<label for="name">{{ __('Nombre de usuario') }}</label>
<input id="name" type="text" class="form-control #error('name') is-invalid #enderror" name="name" value="{{Auth::user()->name}}" autocomplete="name" maxlength="30" autofocus placeholder="Introduce tu nombre de usuario" required>
#error('name')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-group ml-5 mr-5">
<label for="name">{{ __('Dirección de correo:') }}</label><br>
<label for="email">{{Auth::user()->email}}</label>
</div>
<div class="form-group row mb-0">
<div class="col text-center">
<button type="submit" class="btn2 mt-2 mb-3">
{{ __('Actualizar') }}
</button>
<button type="default" class="btn2 mt-2 mb-3">
{{ __('Cancelar') }}
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
This is UsuarioController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
use App\Models\Role;
class UsuarioController extends Controller
{
public function __construct()
{
//permitir solo usuarios autenticados
$this->middleware('auth');
}
public function index()
{
//
}
public function create()
{
//
}
public function store(Request $request)
{
}
public function show($id)
{
}
public function edit($id)
{
$usuario=User::find($id);
if ($usuario== null)
return Redirect::to('usuario');
return view('usuarios.edit')->with('id',$id);
}
public function update(Request $request, $id)
{
$user = User::find($id);
$user->name = Input::get('name');
$user->email = Input::get('email');
$user->password = Input::get('password');
$user->save();
}
public function destroy($id)
{
//
}
}
If someone can give me a hand, I will thank them very much!

Thanks for the answers, I already fixed the error.
I had two controllers using the same controller class and I was working with one and laravel with another.

I do not know exactly where the problem comes from but I think
1: change route
{{route('usuarios.update',auth()->user()) }}
2: It needs a model but you send slug usuarios/{usuario}

Related

Can't login using Laravel with correct credentials

Good day, I've been having a hard time solving this problem for almost a week now. I'm trying to login my Laravel project, the problem is it doesn't login even though the email and password (hashed in db) input is correct. Any help will be greatly appreciated. Below are the code of my files for LoginController.php, login.blade.php, and web.php
LoginController.php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Auth;
use DB;
use App\Models\Distributor;
use Carbon\Carbon;
use Session;
use Brian2694\Toastr\Facades\Toastr;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = RouteServiceProvider::HOME;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except([
'logout',
'locked',
'unlock'
]);
}
public function login()
{
return view('auth.login');
}
public function username(){ return 'email_address';
}
public function authenticate(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['emailAddress'=>$email,'password'=>$password,])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('orders.sellload');
}elseif (Auth::attempt(['emailAddress'=>$email,'password'=>$password])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('orders.sellload');
}elseif (Auth::attempt(['emailAddress'=>$email,'password'=>$password,])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('admin.distributor');
}
elseif (Auth::attempt(['emailAddress'=>$email,'password'=>$password])) {
Toastr::success('Login successfully :)','Success');
return redirect()->intended('admin.distributor');
}else{
Toastr::error('fail, WRONG USERNAME OR PASSWORD :)','Error');
return redirect('login');
}
}
public function logout()
{
Auth::logout();
Toastr::success('Logout successfully :)','Success');
return redirect('login');
}
}
login.blade.php
#extends('layouts.app')
#section('content')
<div id="auth">
<div class="row h-100">
<div class="col-lg-3 col-12">
</div>
<div class="col-lg-6 col-12">
<div id="auth-left">
<p style="text-align:center;"><img src="assets/images/logo/icon.png" width="300" align>
</p>
{{-- message --}}
{!! Toastr::message() !!}
<p style="text-align:center;">Welcome to John Doe Portal</p>
#if(session()->has('error'))
<div class="text-danger text-center text-bold">
{{ session()->get('error') }}
</div>
#endif
<br>
<form method="POST" action="{{ route('login') }}" class="md-float-material">
#csrf
<div class="form-group position-relative has-icon-left mb-4">
<input type="text" class="form-control form-control-lg #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" placeholder="Enter email">
<div class="form-control-icon">
<i class="bi bi-person"></i>
</div>
#error('email')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-group position-relative has-icon-left mb-4">
<input type="password" class="form-control form-control-lg #error('password') is-invalid #enderror" name="password" placeholder="Enter Password">
<div class="form-control-icon">
<i class="bi bi-shield-lock"></i>
</div>
#error('password')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-check form-check-lg d-flex align-items-end">
<input class="form-check-input me-2" type="checkbox" value="remember_me" id="remember_me" name="remember_me">
<label class="form-check-label text-gray-600" for="flexCheckDefault">
Keep me logged in
</label>
</div>
<button class="btn btn-primary btn-block btn-lg shadow-lg mt-5">LOG IN</button>
</form>
</div>
</div>
<div class="col-lg-3 col-12">
</div>
</div>
</div>
#endsection
web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PhotosController;
use App\Http\Controllers\Auth\LoginController;
use App\Http\Controllers\Auth\RegisterController;
use App\Http\Controllers\ResetPasswordController;
use App\Http\Controllers\FormController;
use App\Http\Controllers\UserManagementController;
use App\Http\Controllers\LockScreen;
Route::get('/', function () {
return view('auth.login');
});
Route::get('/insert', function () {
$activationCodeParam=123456;
$idParentParam=1;
$tierParam=2;
$store = DB::select('
call createStore(?,?,?)',
array(activationCodeParam,idParentParam,tierParam));
});
Route::group(['middleware'=>'auth'],function()
{
Route::get('user',function()
{
return view('orders.sellload');
});
Route::get('home',function()
{
return view('orders.sellload');
});
});
Auth::routes();
Route::get('home',function()
{
return view('orders.sellload');
});
// ----------------------------- home dashboard ------------------------------//
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
// -----------------------------login----------------------------------------//
Route::get('/login', [App\Http\Controllers\Auth\LoginController::class, 'login'])->name('login');
Route::post('/login', [App\Http\Controllers\Auth\LoginController::class, 'authenticate']);
Route::get('/logout', [App\Http\Controllers\Auth\LoginController::class, 'logout'])->name('logout');
You are missing the session refresh before your redirect.
// validation here
if(Auth::attempt(['emailAddress'=>$email,'password'=>$password,])) {
Toastr::success('Login successfully :)','Success');
$request->session()->regenerate(); // refresh session
return redirect()->intended('orders.sellload');
}
// …
This shouldn’t be related, but also your if-conditions don’t make sense — because they are all the same and if one matches, the other never can be reached.
Have you tried changing
if (Auth::attempt(['emailAddress'=>$email,'password'=>$password,]))
emailAddress
to email?

How to allow user to edit posts? I am using laravel 8

I am trying to allow users to edit posts, however I keep getting this error:
Property [caption] does not exist on this collection instance. (View: C:\xampp\htdocs\myprojectname\resources\views\posts\edit-post.blade.php)
My edit function in Post Controller is:
use App\Models\Post;
public function edit(Post $post)
{
return view('posts.edit-post', ['post' => $post]);
}
My update function in Post Controller is:
public function update(Post $post, Request $request)
{
$data = request()->validate([
'caption' => 'nullable',
'url' => 'nullable',
'image' => 'nullable',
]);
$updateData = [
'caption' => $data['caption'],
'url' => $data['url'],
];
if (request('image')) {
$imagePath = request('image')->store('uploads', 'public');
$updateData['image'] = $imagePath;
}
auth()->user()->posts()->id()->update($updateData);
return redirect('/users/' . auth()->user()->id);
}
My edit-post.blade.php file code is:
#section('content')
<body class="create_body">
<div class="create_container_div">
<form action="{{('/users/' . auth()->user()->id)}}" enctype="multipart/form-data" method="post">
#csrf
#method('PATCH')
<div class="form-group">
<label for="caption" class="create_caption_label">Post Caption</label>
<div class="create_caption_div">
<input id="caption"
type="text"
class="form-control #error('caption') is-invalid #enderror"
name="caption"
value="{{ old('caption') ?? auth()->user()->posts->caption }}"
autocomplete="caption" autofocus>
#error('caption')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="form-group">
<label for="url" class="edit_title_label">URL</label>
<div class="edit_url_div">
<input id="url"
type="text"
class="form-control #error('url') is-invalid #enderror"
name="url"
value="{{ old('url') ?? auth()->user()->posts->url }}"
autocomplete="url" autofocus>
#error('url')
<div class="invalid-feedback-div">
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
</div>
#enderror
</div>
</div>
<div class="create_post_image_div">
<label for="image" class="create_image_label">Post Image</label>
<input type="file" class="form-control-file" id="image" name="image">
#error('image')
<div class="invalid-feedback-div">
<strong>{{ $message }}</strong>
</div>
#enderror
<div class="create_post_btn_div">
<button class="create_post_btn">Save Changes</button>
</div>
</div>
</form>
</div>
</body>
#endsection
My create_posts_table migration file is:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('url');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
And my Post.php model file is:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
}
}
Finally my routes in web.php are:
use App\Http\Controllers\PostsController;
Route::get('/posts/{post}/edit', [PostsController::class, 'edit']);
Route::patch('/posts/{post}', [PostsController::class, 'update'])->name('posts.update');
How can I resolve this issue, and furthermore, how do I allow users to edit posts?
This line is not correct, i don't know if you are coming from some other language, this makes no sense at all for me.
auth()->user()->posts()->id()->update($updateData);
You have the Post already in the context you are, due to it being Model bound in your controller method public function update(Post $post, Request $request), you can use that to just update it. fill() applies you $updateData to the model and save() writes it to the database.
$post->fill($updateData);
$post->save();
As the comments stated, the edit function is missing an id, again you have already bound your model to the method, then just use it.
public function edit(Post $post)
{
return view('posts.edit-post', ['post' => $post]);
}

Route that handles registration request return 404

I'm trying to let someone register but when I click the register button I get 404 not found.
I've had this issue before but that was cuz of how the routes were ordered but as you can see I only have 2 in this project and the csrf is also implemented as required...
My form:
<!-- register form -->
<div class="col-md-6">
<h2>Register</h2>
<form method="post" action="{{ route('register') }}">
#csrf
<div class="form-group">
<label for="username">Your username</label>
<input type="text" class="form-control" name="username">
#if ($errors->has('username'))
<br><span class="text-danger">{{ $errors->first('username') }}</span>
#endif
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" class="form-control" name="email">
#if ($errors->has('email'))
<br><span class="text-danger">{{ $errors->first('email') }}</span>
#endif
</div>
<div class="form-group">
<label for="password">Your password</label>
<input type="password" class="form-control" name="password">
#if ($errors->has('password'))
<br><span class="text-danger">{{ $errors->first('password') }}</span>
#endif
</div>
<div class="form-group">
<label for="repeat-password">Repeat your password</label>
<input type="password" class="form-control" name="repeat-password">
#if ($errors->has('repeat-password'))
<br><span class="text-danger">{{ $errors->first('repeat-password') }}</span>
#endif
</div>
<input type="submit" class="btn btn-primary" value="Register">
</form>
</div>
My web.php file with my routes:
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'PagesController#index')->name('home');
Route::post('/register', 'PagesController#register')->name('register');
This is my controller handling the functions:
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\RegistrationRequest;
class PagesController extends Controller
{
public function index() {
return view('pages.home');
}
public function register(RegistrationRequest $request) {
$user = new User;
$user->username = $request->input('username');
$user->email = $request->input('email');
$user->password = $request->bcrypt(input('password'));
$user->save();
session()->flash('status', 'Your account has been created!');
return Redirect::back();
}
}
Lastly the registration request:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class RegistrationRequest 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 [
'name' => 'required|min:3|max:30',
'email' => 'email|unique:users',
'password' => 'required|confirmed|min:6'
];
}
}
So apperantly after installing the ui package all my custom routes stopped working. So starting a new project with the same code except the package works.

laravel 5.6 MethodNotAllowedHttpException validate in login

I have a problem with my validation in the login method.
Indeed, the problem is when I try to validate (with the validate method) my login by entering wrong login (I want to see the error messages) but the problem appears when it tries to redirect me back.
here is the login
view :
html :
<div class="container-fluid">
<div class="row justify-content-center">
<form method="POST" action="{{ route('login') }}" aria-label="{{ __('Login') }}">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div class="form-group row">
<label for="username" class="col-sm-4 col-form-label text-md-right">{{ __('E-Mail Address') }}</label>
<div class="col-md-6">
<input id="username" type="text" class="form-control{{ $errors->has('username') ? ' is-invalid' : '' }}" name="username" value="{{ old('username') }}" required autofocus>
#if ($errors->has('username'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('username') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<label for="mdp" class="col-md-4 col-form-label text-md-right">{{ __('mot de passe') }}</label>
<div class="col-md-6">
<input id="mdp" type="password" class="form-control{{ $errors->has('mdp') ? ' is-invalid' : '' }}" name="mdp" required>
#if ($errors->has('mdp'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('mdp') }}</strong>
</span>
#endif
</div>
</div>
<div class="form-group row">
<div class="col-md-6 offset-md-4">
<div class="form-check">
<input class="form-check-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="form-check-label" for="remember">
{{ __('se souvenir de moi') }}
</label>
</div>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-8 offset-md-4">
<button type="submit" class="btn btn-primary">
{{ __('Login') }}
</button>
<a class="btn btn-link" href="{{ route('password.request') }}">
{{ __('Forgot Your Password?') }}
</a>
</div>
</div>
</form>
</div>
</div>
Error :
the method of login :
class LoginController extends Controller
{
public function login(Request $request){
$this->validate($request, [
$this->username() => 'required|string|email|max:255',
'mdp' => 'required|string|min:6',
],$message);
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if ($this->attemptLogin($request)) {
return $this->sendLoginResponse($request);
}
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
}
the route :
Route::get('/', PATH_CENTRA_UTILISATEUR.'VerificationController#index')->name('verification_index');
Route::post('/verification',PATH_CENTRA_UTILISATEUR.'VerificationController#verifier')->name('verification_verifier');
Auth::routes();
And the list of route
You can help me, thank you all.
Your code is already mentioned in a Trait.
Please find below code.
LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use App\Http\Repository\RolePermissionRepository;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use Closure;
use Carbon\Carbon;
use Illuminate\Foundation\Application;
use Symfony\Component\HttpFoundation\Cookie;
use Illuminate\Contracts\Encryption\Encrypter;
use Illuminate\Session\TokenMismatchException;
use Illuminate\Support\Facades\Password;
use App\User;
use DB;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct(Request $chekker)
{
// \Visitor::log(); //log in db visitor ip, geo location, hit counter
$this->middleware('guest')->except('logout');
}
}
This should solve your problem.
web.php
Auth::routes();
// please dont add this in any middleware
And check in this file vendor/laravel/framework/src/Illuminate/Routing/Router.php. => auth method if there are all routes are mentioned or not.
if nothing works. Please clear route cache and conf cache.
in worse case, try restarting your machine.
EDIT
Please see sample overriding of login method.
public function login(Request $request)
{
$remember = $request->has('remember');
$this->validateLogin($request);
if ($request->get('user_check') == '' || $request->get('user_check') == null) {
$checker = user::where("email",$request->email)->first();
if ($checker) {
//$this->checkInActive($request);
if (Auth::attempt(['email' => $checker->email, 'password' => $request->get('password'), 'id' => $checker->id] , $remember)) {
return redirect('/home');
} else {
return $this->sendFailedLoginResponse($request);
}
} else {
return $this->sendFailedLoginResponse($request);
}
}
}

laravel 5.2 signup probleme

I'm working on laravel 5.2 shopping cart site and i have this sign up problem when i put an email address and a password to signup it tells me that password is required. but i filed the password place
the view signup
this is my user controller
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function getSignup(){
return view('user.signup');
}
public function postSignup(Request $request){
$this->validate($request,['email'=>'email|required|unique:users',
'password'=>'required|min:4',
]);
$user=new User([
'email'=> $request->input('email'),
'password'=>bcrypt($request->input('password'))
]);
$user->save();
return redirect()->route('product.index');
}
public function getSignin(){
return view('user.signin');
}
public function postSignin(Request $request){
if(Auth::attempt(['email'=>$request->input('email'), 'password'=>$request->input('password')])){
return redirect()->route('user.profile');
}
return redirect()->back();
}
public function getProfile(){
return view('user.profile');
}
}
Could you please post the view?, check if in the view you are putting to the password input the same name you are trying to get in the controller action
this is the view of signup controller
#extends('layouts.master')
#section('content')
<div class="row">
<div class="col-lg-4 col-lg-offset-4">
<h1>Sign Up</h1>
#if(count($errors)>0)
#foreach($errors->all() as $error)
<div class="alert alert-danger form-group">
<p>{{$error}}</p>
</div>
#endforeach
#endif
<form action="{{route('user.signup')}}" method="post">
<div class="form-group">
<label for="email">E-mail</label>
<input type="email"id="email" name="email" class="form-control">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="Password" name="Password" class="form-control">
</div>
<button class="btn btn-primary" type="submit">Sign Up</button>
{{csrf_field()}}
</form>
</div>
</div>
#endsection

Categories