What does "Method [show] does not exist" mean? - methods

I'm new to Laravel 4 and trying to figure out why I'm getting an error saying that Method [show] does not exist.
I do not have a method named "show" and can only imagine that this is an internal, Laravel method but I do not know how to affect this or what could have done this. Any thoughts or help on this would be incredibly appreciated as I have been stuck on this for two days now and cannot figure out what I am doing wrong.
View:
<li>Sign in</li>
Route:
/*Sign In (GET)*/
Route::get('/account/sign-in', array(
'as' => 'account-sign-in',
'uses' => 'AccountController#getSignIn'
));
AccountController:
class AccountController extends BaseController {
public function getSignIn(){
return View::make('user.signIn');
}
public function postSignIn(){
$validator = Validator::make(Input::all(), array( 'email' => 'required|email', 'password' => 'required' ) );
if($validator->fails()){ /*Redirect to the sign in page*/
return Redirect::route('account-sign-in') ->withErrors($validator) ->withInput();
}
else { /*Attempt user sign in*/
$remember = (Input::has('remember')) ? true : false;
$auth = Auth::attempt(array( 'email' => Input::get('email'), 'password' => Input::get('password'), 'active' => 1 ), $remember);
if($auth){
/*Redirect to the intended page*/ return Redirect::intended('/');
}
else {
return Redirect::route('account-sign-in')->with('global', 'Email/password wrong, or account not activated.');
}
}
return Redirect::route('account-sign-in') ->with('global', 'There was a problem signing you in.');
}
}

What does “Method [show] does not exist” mean?
Code provided in your question doesn't shows anything about show() method, anyways. According to to your comments you didn't extend the BaseController but all your controlers should extend the BaseController and the BaseController should extend the Controller so this is how your BaseController should look like (By default):
class BaseController extends Controller {
/**
* Setup the layout used by the controller.
*
* #return void
*/
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
}
Your controller should extend it like this:
class AccountController extends BaseController {
// Define all of your methods
// including show() if you are using it
}

It sounds like you just have a typo on the first line of your AccountController
It probably says class AccountController extends BasesController {
BasesController should be BaseController

I had this problem. I had previously listed a (now deprecated) resource that was causing a collision in the routes.php file.
Route::resource('scheduler', 'SchedulerController');
Route::get('scheduler/notices', 'SchedulerController#notices');

Related

Laravel redirect in controller from another class

I try co redirect to other route in controller, unfortunately dont work.
My idea is redirect to 'home' when conditions in method canStart from my service class are realize.
My controller
public function start($id) {
$user = auth()->user();
$this->testService->canStart($id);
//do something ...
return view('common/start/',
[
'id' => $id,
'data' => $data,
'logs' => $logs
]);
}
Other Class method
public function canStart($id) {
return redirect()->route('home');
}
public function canStart($id) {
return redirect()->route('home')->send();
}
It work now

How to return custom response when validation has fails using laravel form requests

When we use Laravel Form Requests in our controllers and the validation fails then the Form Request will redirect back with the errors variable.
How can I disable the redirection and return a custom error response when the data is invalid?
I'll use form request to GET|POST|PUT requests type.
I tried the Validator class to fix my problem but I must use Form Requests.
$validator = \Validator::make($request->all(), [
'type' => "required|in:" . implode(',', $postTypes)
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()]);
}
Creating custom FormRequest class is the way to go.
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;
class FormRequest extends \Illuminate\Foundation\Http\FormRequest
{
protected function failedValidation(Validator $validator)
{
if ($this->expectsJson()) {
$errors = (new ValidationException($validator))->errors();
throw new HttpResponseException(
response()->json(['data' => $errors], 422)
);
}
parent::failedValidation($validator);
}
}
Class is located in app/Http/Requests directory. Tested & works in Laravel 6.x.
This is the same but written differently:
protected function failedValidation(Validator $validator)
{
$errors = (new ValidationException($validator))->errors();
throw new HttpResponseException(
response()->json([
'message' => "",
'errors' => $errors
], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
);
}
Base class FormRequest has method failedValidation. Try to override it in your FormRequest descendant
use Illuminate\Contracts\Validation\Validator;
class SomeRequest extends FormRequest
{
...
public function failedValidation(Validator $validator)
{
// do your stuff
}
}
use this on function
dont forget to take on top // use App\Http\Requests\SomeRequest;
$validatedData = $request->validated();
\App\Validator::create($validatedData);
create request php artisan make:request SomeRequest
ex.
use Illuminate\Contracts\Validation\Validator;
class SomeRequest extends FormRequest
{
public function rules()
{
return [
'health_id' => 'required',
'health' => 'required',
];
}
}

laravel UserRequest $request error

laravel5.2,I create a UserRequest.php under Requests directory,but in controller,public function add(UserRequest $request) show error,but use public function add(Request $request) is normal.
UserRequest
namespace App\Http\Requests;
use App\Http\Requests\Request;
class UserRequest extends Request
{
/**
* 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 [
'user_sn' => 'required|unique',
'user_name' => 'required',
'email' => 'required|unique',
'password' => 'required',
];
}
}
UserController
namespace App\Http\Controllers;
use App\Http\Requests\UserRequest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
public function add(UserRequest $request)
{
if ($request->get('dosubmit')) {
$validator = Validator::make($request->all(), $request
->rules(), $request->messages());
if ($validator->fails()) {
return redirect('user/add')->withErrors($validator)
->withInput();
}
}
$corporation_list = DB::table('corporation')->get();
$department_list = DB::table('department')->get();
return view('user.add', ['corporation_list' => $corporation_list, 'department_list' => $department_list]);
}
}
Route
Route::group(['middleware'],function (){
Route::any('user/add',['as'=>'user.add','uses'=>'UserController#add']);
});
There are usually 2 reasons you could be having this issue.
You've not added the use statement for the UserRequest.
At the top of your controller (above the class) add:
use App\Http\Requests\UserRequest
assuming that is the correct namespace.
You may need to run composer dump-autoload to make sure the class has been added to the autoloader.
Edit
Firstly, replace the add() method with the following methods:
public function create()
{
$corporation_list = DB::table('corporation')->get();
$department_list = DB::table('department')->get();
return view('user.add', compact('corporation_list', 'department_list'));
}
public function store(UserRequest $request)
{
// If you get to this point the validation will have passed
// Process the request
}
Then change your routes from:
Route::any('user/add',['as'=>'user.add','uses'=>'UserControl‌​ler#add'])
to:
Route::get('user/add', ['as' => 'user.add', 'uses' => 'UserControl‌​ler#create']);
Route::post('user/add', ['as' => 'user.store', 'uses' => 'UserControl‌​ler#store']);
Obviously, feel free to change the as in the Routes to whatever, they should unique though.
Lastly, I would suggest looking at Resource Controllers which is a RESTful approach.
The problem is that you have not identified UserController that you are using UserRequest file
use App\Http\Requests\UserRequest
It will solve the problem

Login using laravel5.2

Hi I'm new to laravel and I'm using the laravel5.2 version.
Actually I have this registration form too. But no problem in registration.
My question is that I'm looking for a simple and understandable code in login. I've seen it somewhere while googling but I think that one is not laravel5.2.
I just get the reference code in some examples and test it into my login app. I'm using a repositories on it. I've got some errors. It says
Whoops, looks like something went wrong.
1/1 FatalErrorException in EloquentUserProvider.php line 126: Class '\App\User' not found
I'm not sure why the error says app user not found. Here is my code below
<?php
namespace App\Repositories;
use App\Repositories\Contracts\loginRepositoryInterface;
use Illuminate\Http\Request;
use App\Users;
use DB;
use Session;
use Auth;
class loginRepository implements loginRepositoryInterface{
protected $request;
//Initialize request instance
public function __construct(Request $request){
$this->request = $request;
}
public function loginAuth(){
//validate login
$validator = app('validator')->make($this->request->all(), [
'emailAddress' => 'email|required',
'password' => 'required']);
//if validator fails then return response error
if($validator->fails())
return redirect()->route('get.login')->withErrors($validator)->withInput();
try{
$pwd = $this->request->get('password');
$sha1 = sha1($pwd);
$userdata = array(
'emailAddress' =>$this->request->get('emailAddress'),
'password' =>$sha1
);
if(Auth::attempt($userdata)){
return redirect()->intended('get.dashboard');
}else{
return redirect()->route('get.login')->withErrors($validator)->withInput();
}
}catch(\Exception $e){
return redirect()->route('get.login')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
//postCreate
public function postCreate($screen){
switch($screen){
case 'auth':
return $this->loginAuth();
break;
}
}
//getLoginView
public function getCreate(){
return view('login');
}
}
In method public function loginAuth()
My routes
//postLogin
Route::post('/login/{screen}', [
'as' => 'post.login.auth',
'uses' => 'loginController#postCreate'
]);
//getLoginView
Route::get('/login', [
'as' => 'get.login',
'uses' => 'loginController#getCreate'
]);
Can some one help me on this?
Thanks.
Make sure you have the \App\User model in app/User.php from the looks of the code you posted above, you seem to have \App\Users not \App\User

Cake PHP 2.x Auth data is only available in one controller and null in the rest. Any idea why?

I am new to CakePHP, and despite searching high and low I can't find an answer to what seems like a trivial problem. The issue is that after logging in through my UserController I am losing the data found in $this->Auth->user() on all other Controllers. Any views not associated with UserController will always have null data and $this->Auth->loggedIn() will return false.
In my AppController class, I have attempted to save the data into a variable inside beforeFilter() so that I may check the variable in my views, but it doesn't make a difference. Here is the relavent code for my UserController and AppController classes:
class AppController extends Controller {
// Pass settings in $components array
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'home', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'home', 'action' => 'index')
)
);
public function beforeFilter() {
//debug($this->Auth->user());
$this->set('loggedIn', $this->Auth->user());
}
}
Users class:
App::uses('AppController', 'Controller');
class UsersController extends AppController {
public $helpers = array('Html', 'Form');
public $name = 'Users';
public function beforeFilter() {
parent::beforeFilter();
}
public function login() {
if ($this->request->is('post')) {
if ($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
public function logout() {
return $this->redirect($this->Auth->logout());
}
}
I have also made sure to use parent::beforeFilter() in my other controllers.
I believe I found the solution. In my HomeController, which was the page I was always viewing after I logged in, it seems as though there was some invisible character following the closing php declaration ?> (which was not needed either) so I deleted it and the ?> and voila, everything is working as expected.
I was tipped off that something was amiss after I tried manually using session_start() in my layout and I was given an error about the line after ?> in the HomeController class.
I think you should set loggedIn in the beforeRender() function in your AppController class instead of beforeFilter().
public function beforeRender() {
$this->set('loggedIn', $this->Auth->user());
}

Resources