Laravel 5 input::get error - php

Why am I having this error? I tried to add use Illuminate\Http\Request;
but same error? Also is $username = $request->input('username'); the same as $username = Input::get('username');?
The error I get is:
FatalErrorException in LoginController.php line 22: Class 'App\Http\Controllers\Input' not found
class LoginController extends Controller {
// Display the login form
public function showLogin()
{
return View::make('login');
}
// Process submission of the login form by verifying user’s credentials
public function processLogin()
{
$username = Input::get('username');
$password = Input::get('password');
if ($username === 'prince' && $password === 'c#spiAN') {
return 'Access granted!';
} else {
return 'Access denied! Wrong username or password.';
}
}
}

Add use Input; after Namespace ... and then use as Input::get(..) or don't add use and call \Input::get(..). Find more here: http://php.net/manual/pl/language.namespaces.php

You have to follow the namespace, as others told you in the comments.
Imagine it as a capitalized folder structure, now you are under App\Htt\Controllers, so it looks for App\Http\Controllers\Input.
Anything that is not directly under the same namespace must be referenced before the class declaration or prefixed with the full namespace adding a backslash \ at the beginning.
It depends on how many times you need to use it. If just once, then call it using the full path from the root. In this case it would be \Input (\Input::get(...)), otherwise reference it on the top and call it like you did in the question's code.
To better understand, in case of a model you'd need to call the class User as use App\User; on the top or directly as \App\User::all()(as example) inline in your method's code.

Related

Fatal error: Class 'App\User' not found in public_html/laravel/app/CreateUser.php

I did a very simple CreateUser.php under app folder as follows.
$user = new App\User;
$user->name='John Doe';
$user->email='john#example.com';
$user->password=bcrypt('password');
But I got error message Fatal error: Class 'App\User' not found in public_html/laravel/app/CreateUser.php. Any ideas? TIA.
You have to include User model first to work your query. See the link below, you will get good idea how to use it.
https://laravel.com/docs/5.2/controllers
Put this in your routes
Route::get('/createuser', function () {
'as' => 'createuser',
'uses' => 'UserController#creteUser'
});
In your controller create UserController.php
use App\User;
public function creteUser(User $user)
{
$user->name='John Doe';
$user->email='john#example.com';
$user->password=bcrypt('password');
$result = $user->save();
if($result){
return redirect ('createuser')->with('success', 'User Created Successfully');
}
return redirect ('createuser')->with('error', 'Failed to create User');
}
Have You tried
$user = new User;
instead of
$user = new App\User;
and, Make sure you are created model (User)and also specify namespace (use App\User) at the top of your controller.

Namespace declaration statement has to be the very first statement in the script

I just started to develop web application with Laravel, I have a problem to use the dependency injection. It works fine without the DI, but I want to refactor the code so that the code is not tightly coupled.
I already search in google that suggests perhaps there is a white space before the namespace and search related questions here, but none of them solve my problem.
AccountController
<?php
namespace TabJut\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Validator;
use View;
use TabJut\Http\Requests;
use TabJut\Http\Controllers\Controller;
use TabJut\Repositories\AccountRepository;
class AccountController extends Controller
{
/* error culprit, If I remove these the page not error */
protected $repository;
public function __construct(AccountRepository $repository)
{
$this->repository = $repository;
}
/* error culprit */
public function getLogin()
{
return View::make('account.login');
}
public function postLogin()
{
// Validates inputs.
$rules = array(
'username' => 'required',
'password' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// Redirects back to the form if the validator fails.
if ($validator->fails()) {
return Redirect::action('AccountController#getLogin')
->withErrors($validator)
->withInput(Input::except('password'));
}
$username = Input::get('username');
$password = Input::get('password');
$user = $repository.Authenticate($username, $password);
var_dump($user);
}
}
AccountRepository
<?php
namespace TabJut\Repositories;
use DB;
class AccountRepository
{
public function Authenticate($username, $password)
{
$user = DB::table('users')
->where('is_active', '1')
->where('user_name', $username)
->where('password', $password)
->first();
return $user;
}
}
Folder Tree
Error Message
FatalErrorException in AccountRepository.php line 3: Namespace
declaration statement has to be the very first statement in the script
in AccountRepository.php line 3
at FatalErrorException->__construct() in HandleExceptions.php line 127
at HandleExceptions->fatalExceptionFromError() in HandleExceptions.php line 112
at HandleExceptions->handleShutdown() in HandleExceptions.php line 0
at Composer\Autoload\includeFile() in ClassLoader.php line 301
Did I miss any important configuration like service locator setup or just unseen code error?
Please help.
It has nothing to do with the dependency injection, based on kuzawinski comment on the manual, I recreated the file with notepad and it solves the problem.
...and you still get "Namespace declaration statement has to be the
very first statement in the script" Fatal error, then you probably use
UTF-8 encoding (which is good) with Byte Order Mark, aka BOM (which is
bad). Try to convert your files to "UTF-8 without BOM", and it should
be ok. Comment

Logging a user in manually on Laravel 5

I'm using facebook JS to log in users to a laravel 5 application.
I'm able to add the information to the database correctly but I'm trying to log the user in manually and can't figure it out.
Here is my controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\lib\TopAdditions;
use App\Http\lib\GeneralFunctions;
use App\User;
class FacebookLoginController extends Controller{
public function FacebookRegistration(){
$facebook = new User();
$isThereAUser = User::where('name', $_GET['name'])->get();
if(!count($isThereAUser) > 0){
$facebook->name = $_GET['name'];
$facebook->email = $_GET['email'];
$facebook->password = sha1($_GET['password']);
$facebook->remember_token = $_GET['token'];
$facebook->save();
$id = User::where('name', $_GET['name'])->get();
$this->LoginUser($id);
}
}
public function LoginUser($id){
\Auth::login($id[0]['id'],true);
}
}
When I run that and there is no such user in the database, the user is created and I get this message when the manual login is attempted:
ErrorException in Guard.php line 425:
Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, integer given
I've been searching the web for similar situations but couldn't find anything that will help...
Please help me!
You should pass the user object, not the id, to Auth::login. So just change your function to be like this:
public function LoginUser($user){
\Auth::login($user, true);
}
I had the same problem, this is the solution that worked for me in Laravel 5.4:
public function LoginUser($id){
$user = User::find($id);
auth()->login($user);
}

Laravel controller doesn't exist

Ok, so I haven't had this issue in a while, but I've done most the options I can to resolve this and have read other people's posts. I'm at a lost right now.
After creating the controller, I did the "php ./composer.phar dump-autoload" command, saying it generated successfully, and it's still saying the controller doesn't exist. There are already 3 other controllers in the folder it's in, and each one of those works, it's just this controller that's having the problem.
Code to Controller: (/apps/controllers/api/apiBulkController.php)
class apiBulkController extends BaseController {
private $error;
public function __construct()
{
// Set default values
$this->error = 'false';
}
public function create()
{
$bulk = array();
// Authenticate the user using the api
if (!isset($_SERVER['PHP_AUTH_USER'])) {
$this->authenticate();
} else {
$auth = User::where('username', $_SERVER['PHP_AUTH_USER'])->first();
// Check to see if the user is valid
if(isset($auth->authkey) && $auth->authkey == $_SERVER['PHP_AUTH_PW'])
{
$req = Request::get();
$bulk = new Bulk;
// Add Columns by example below
$bulk->save();
//ex. $Bulk->Name = Request::get(''); $object->column_name = Request;
// Return JSON data
return Response::json(array(
'error' => $this->error
));
}
else
{
echo $_SERVER['PHP_AUTH_USER'].": Your hash seems to be incorrect.";
}
}
}
public function authenticate()
{
header('WWW-Authenticate: Basic realm="User Authentication (Username / Hash)"');
header('HTTP/1.0 401 Unauthorized');
echo "You must enter a valid Login ID and Hash to access this resource\n";
exit;
}
}
You should probably add
namespace api;
at the beginning of your controller
and run controller also using your namespace before class name, for example in Route api\apiBulkController#create instead of apiBulkController#create.
If error changes, you should then alter your class adding namespaces or uses to other classes for example instead of extends BaseController should be extends \BaseController and so on

CakePhp Error: Call to a member function create() on a non-object

I am currently learning how to use CakePhp.
I have created a function in my custom controller as follows:
class FormatsController extends AppController
{
// ....
function admin_add()
{
// if the form data is not empty
if (!empty($this->data)) {
// initialise the format model
$this->Format->create();
// create the slug
$this->data['Format']['slug'] = $this->slug($this->data['Format']['name']);
// try saving the format
if ($this->Format->save($this->data)) {
// set a flash message
$this->Session->setFlash('The Format has been saved', 'flash_good');
// redirect
$this->redirect(array('action' => 'index'));
} else {
// set a flash message
$this->Session->setFlash('The Format could not be saved. Please, try again.', 'flash_bad');
}
}
}
}
However in my view I am getting this error:
Error: Call to a member function create() on a non-object
Why is this error caused and how can I fix it?
My apologies, I believe the line it is referencing is not in the Controller but in my view itself. It refers to my view which has the following line:
<?php echo $form->create('Format');?>
Is there something else I need to declare before using this? i.e. $this->Format->create();
you should be using:
$this->Form->create('Format');
delete the
<?php echo $form->create('Format');?>
and replace it with
<?php echo $this->Form->create('Format');?>
$form is the one that causes the error.
Need to define the global name of the model. So, to access it anywhere in application.
For example: my model is User
class User extends AppModel {
var $name = 'User';
function myfunction ($id) {
.....
}
}
To use in controller
Controller:
class UsersController extends AppController
{
function test()
{
$this->User->myfunction();
......
}
}
I hope this will help you!
This is probably being caused because for some reason $this->Format isn't being created. If you look in your code snippet you see it calling the create() function. Add this as a debug statement in your controller function before you call create() to see if it is even set.
debug( isset( $this->Format ) );
If it is set should output true. If you try this let me know what it says I might have some other suggestions to go from there.
Have you created the model "Format"?
This kind of errors arise when the called model has a problem. Either it is not created, or it is not properly created or it is not imported/ initiated properly.
If you declared $uses variable in your controller, make sure you include "Format" in your $uses array along the other models.
Try this one into your action
$this->loadModel('Format');
$this->Format
is undefined (so it's value is null), a null object has no functions, therefor you can't use
$this->Format->create();
It's pretty much equal to
null->create();
Try
$this->Form->create(null,['url' => ['controller' => 'yourController', 'action' => 'yourAction']])

Categories