I have the following test to check my simple crud application in laravel.
I have my SalesManagersTest.php in tests/features
<?php
use App\Providers\RouteServiceProvider;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;
class SalesManagersTest extends TestCase
{
use RefreshDatabase;
public function test_can_see_index_screen()
{
$response = $this->get('/salesmanagers');
$response->assertStatus(200);
}
public function test_can_see_add_record_screen()
{
$response = $this->get('/salesmanagers/create');
$response->assertStatus(200);
}
public function test_can_add_new_record()
{
$response = $this->POST('/salesmanagers/create', [
'_token' => csrf_token(),
'full_name' => 'Test User',
'email' => 'test#example.com',
'telephone' => '0775678999',
'current_route' => 'Negombo',
'joined_date'=>'2022/09/12',
'comments' => 'Test comment'
]);
$response->assertStatus(200);
$response->assertRedirectedTo('salesmanagers');
}
}
The first two tests work well but the third test is giving me an error
but since I'm trying to insert new record the method has to be POST
this is my web.php
Route::get('/', [ SalesManagersController::class, 'index' ]);
Route::resource('salesmanagers', SalesManagersController::class);
Route::get('salesmanagers.create', [ SalesManagersController::class, 'create' ]);
Route::post('salesmanagers.create', [ SalesManagersController::class, 'store' ]);
What could be the the issue with my test?
The issue is your route definition. It appears you're using a route name for the URI of your route. Change your route to the following and try again:
Route::post('/salesmanagers', [SalesManagersController::class, 'store']);
Oh and POST your data to /salesmanagers not salesmanagers/create.
Related
I have a very basic Codeigniter 4 REST API with only one user and one function (POST). I need to add basic authentication where the username and password are in the HTTP authentication header. How do I add that to the code below? i don't need anything very sophisticated, just enough to authenticate the one user.
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\ApiModel;
use Config\Services;
class Api extends ResourceController {
use ResponseTrait;
protected $request;
public function create() {
$model = new ApiModel();
$data = [
'uid' => $this->request->getPost('uid'),
'request' => $this->request->getPost('request'),
'data' => $this->request->getPost('data')
];
$model->insert($data);
$response = [
'status' => 201,
'error' => null,
'messages' => [
'success' => 'Data Saved'
]
];
return $this->respondCreated($data, 201);
}
}
A few days ago I started learning laravel 7.
I bought a course on udemy.
I got to the part where the real registry system went and started to rewrite the code like in the video, but when I do it I get an error!
Error Message: "Class 'App\Http\Controllers\Validator' not found"
I've been trying to fix this for hours, and I'm not doing well
AccountController.php
<?php
namespace App\Http\Controllers;
class AccountController extends Controller
{
public function getcreate(){
return view('account.create');
}
public function postcreate(){
$validator = Validator::make(Input::all(),
array(
'email' => 'required|max:50|email|unique:users',
'username' => 'required|max:20|min:3|unique:users',
'password' => 'required|min:6',
'repeat_pass' => 'required|same:password'
));
if($validator->fails()){
die('ERROR');
}
else{
die('Cool');
}
}
}
you need to import validator namespace
use Illuminate\Support\Facades\Validator;
then instead of Input you could use request()->all() helper function
so it will be like this
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Validator;
class AccountController extends Controller
{
public function getcreate(){
return view('account.create');
}
public function postcreate(){
$validator = Validator::make(request()->all(),
array(
'email' => 'required|max:50|email|unique:users',
'username' => 'required|max:20|min:3|unique:users',
'password' => 'required|min:6',
'repeat_pass' => 'required|same:password'
));
if($validator->fails()){
die('ERROR');
}
else{
die('Cool');
}
}
}
You will need to import the Validator class from it's correct namespace which is Illuminate\Support\Facades. So goes with Input class. Best way I can suggest is to add these in aliases section in config\app.php like below:
'aliases' => [
// other imports
'Validator' => Illuminate\Support\Facades\Validator::class,
'Input' => Illuminate\Support\Facades\Input::class,
]
Now, you can simply use them in your controller like below:
<?php
namespace App\Http\Controllers;
use Validator;
use Input;
class AccountController extends Controller
{
// rest of your code
}
You can use Validator namespace in your controller at top like:
use Validator;
I am making a test but it fails when it tries to check if a user is logged in:
<?php
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Auth;
use App\User;
class RegisterTest extends TestCase
{
use RefreshDatabase;
/*.....
more test about registering
....*/
/** #test */
function redirect_to_home_page_and_logged_in_after_login()
{
$user = factory(User::class)->create([
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
$response = $this->post('login', [
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
}
And this is my controller HomeController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class HomeController extends Controller
{
public function index()
{
if (Auth::check()){
return view('home');
}
return view('welcome');
}
}
And this is my routes/web.php
Route::get('/', 'HomeController#index');
Auth::routes();
I am not sure what I am doing wrong. What can I do?. I am using laravel 5.7 and phpunit 5.7.1
Also in my app/Htpp/Auth/LoginController.php I did this:
protected $redirectTo = '/';
Thank you.
In addition to hashing your password you could also just post to the register route and create a new account.
/** #test */
function redirect_to_home_page_and_logged_in_after_register()
{
$response = $this->post('register', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
I guess you may also have a requirement to do it both ways:
/** #test */
function redirect_to_home_page_and_logged_in_after_login()
{
$user = factory(User::class)->create([
'name' => 'Test',
'email' => 'test#hotmail.com',
// note you need to use the bcrypt function here to hash your password
'password' => bcrypt('123456')
]);
$response = $this->post('login', [
'name' => 'Test',
'email' => 'test#hotmail.com',
'password' => '123456'
]);
//this works
$response->assertRedirect('/');
//this fails
$this->assertTrue(Auth::check());
}
Creating a user requires you to take care of the hashing of the password.
You can simply do it by using php's password_hash function. And use Auth::login($user); to login.
Like so:
$user = User::create(['email' => 'r#o.b', 'password' => password_hash('123456', 1)]);
Auth::login($user); //You should be logged in :)
I am using Laravel 5.5.40 along with the Zizaco\Entrust Pacakge
In my routes/web.php file i have the following route setup.
Route::group(['prefix' => 'order'], function() {
Route::get('', 'OrderController#getMe');
});
It is supposed to call the getMe() method inside the OrderController.php but it instead redirects to www.mydomain.co.uk/home
namespace App\Http\Controllers;
class OrderController extends Controller
{
public function getMe() {
return "You got me!";
}
}
As a test, I added a __construct function to the OrderController.php to see if the class was even been loaded.
public function __construct() {
dd("Testing");
}
When accessing www.mydomain.co.uk/order i now get
"Testing"
I can't seem to work out why it is not running the getMe() method. Could anyone possibly shine some light on this please?
I have also tried changing the route to use ClientController#list which works fine.
Contents of ClientController.php
namespace App\Http\Controllers;
use App\Client;
class ClientController extends Controller
{
public function __construct() {
//
}
// Display all the clients
public function list() {
$tabContent = [
'display_type' => 'list',
'data' => Client::orderBy('name', 'asc')->get(),
'view_params' => [
'columns' => [
'name' => 'Client Name',
'address_line_1' => 'Address Line 1',
'town' => 'Town',
'county' => 'County',
'post_code' => 'Post Code'
],
'links' => 'client',
'controls' => True
]
];
return view('tables.list', ['data' => $tabContent]);
}
}
It has become apparent that if the controller does not have the constructor function in it, it will automatically redirect to the root of the URI with no error.
public function __construct() {
//
}
I have a static method in User model.
namespace Tol;
...
class User extends Model implements AuthenticatableContract, CanResetPasswordContract
{
...
public static function signup(array $data)
{
$user = new User([
'email' => $data['email'],
'password' => Hash::make($data['password']),
'username' => $data['username'],
'type' => $data['type'],
]);
$user->save();
if ($user && $user->id) {
$profile = new UserProfile([
'first_name' => trim($data['first_name']),
'last_name' => trim($data['last_name']),
'gender' => $data['gender'],
]);
$user->profile()->save($profile);
EmailVerification::sendTo($user, 'signup');
}
return $user;
}
...
}
And I'm trying to call call this method simply from my controllers.
like this
$user = User::signup($input);
And it throws error like this:
I don't know why it is referring it as a method on the Builder class. The code is very simple and everything was working when it was Laravel 4.
Please help.
thanks
your code should have no problem, im afraid the problem is in your auth.php file, please ensure
'model' => 'App\User',
is set it to your model file in your case
'model' => 'Tol\User',
and to ensure your calling the right file you might want to give this a try
\Tol\User::signup($array);