unit testing for Controller's index function - laravel

This is my function :
public function index(Request $request)
{
$data = User::all();
return view('data.index',[
'data' => $data
]);
}
I write a test for this
public function testIndex()
{
$response = $this->call('GET', '/data');
$this->assertEquals(200, $response->status());
}
but not works. Show redirection
Response status code [302] is not a successful status code.
Failed asserting that false is true.
Here is my route:
Route::group(['prefix' => 'data'], function() {
Route::get('/', ['as' => 'data.index', 'uses' => 'DataController#index']);
});
I tried everything but still showing the same thing.

You just need to change your index() method as following :
public function index(Request $request)
{
$data = User::all();
return view('data.index',[
'data' => $data
])->setStatusCode(200);
}
Hope it will helps you. Thanks

Related

How to fix Class not found error while making POST request?

In api.php I've described some routes. GET method works. Can't tell the same about POST method.
<?php
use Illuminate\Http\Request;
use App\UserUnfo;
Route::middleware('auth:api')->get('/user', function (Request $request)
{
return $request->user();
});
Route::get('/person', function() {
$person = [
'ip' => '127.0.0.1',
'name' => 'me'
];
return $person;
});
Route::post('/person', function(Request $request) {
$userInfo = UserInfo::create([
'name' => $request->input('name'),
'ip' => $request->input('ip')
]);
return $userInfo;
});
In web.php
Route::get('/home', 'HomeController#index')->name('home');
The error I've got
Class 'UserInfo' not found
You're using the wrong model it's spell mistake.
use App\UserUnfo;
To
use App\UserInfo;

Class Controller does not exist

I'm trying to make a CRUD (which was working fine in a simple blade) in a new template but it is not showing any page of crud and says not found. If I type: php artisan route:list then it says:
Class App\Http\Controllers\PostsController does not exist
I'm following this tutorial and my folder structure is https://ibb.co/db4WQ8R
Controller
class CrudsController extends Controller
{
public function index()
{
$data = Post::latest()->paginate(5);
return view('adminhome', compact('data'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
public function create()
{
return view('create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'image' => 'required|image'
]);
$image = $request->file('image');
$new_name = rand().'.'.$image->getClientOriginalExtension();
$image->move(public_path('images'), $new_name);
$form_data = array(
'name' => $request->name,
'image' => $new_name
);
Crud::create($form_data);
return redirect('post')->with('success', 'Data Added successfully.');
}
}
Routes
Route::group(['middleware' => ['auth']], function () {
Route::get('/home', function () {
if (Auth::user()->admin === 0) {
return view('home');
}
return view('adminhome');
});
Route::resource('post', 'PostsController');
});
How can I solve it?
In your controller rename Cruds
class PostsController extends Controller
{

Laravel 302 redirect issue

I am trying to get info from action, but when click, just page refresh and in console I get code 302 and stay on current page.
I read a lot of similar topics here but found nothing.
I am trying to execute http://laravel2.lo/getUserChannels?user_id=2
Laravel 5.7.16
route:
Auth::routes();
Route::group(['middleware' => ['auth']], function () {
Route::view('createUser', 'createuser');
Route::view('createChannel', 'createchannel');
Route::view('joinChannel', 'joinchannel');
Route::get('profile', 'UserController#profile');
Route::get('users', 'UserController#users');
Route::get('getChannelUsers', 'UserController#getChannelUsers');
Route::get('getUserChannels', 'ChannelController#getUserChannels');
});
ChannelController:
class ChannelController extends Controller
{
public function getUserChannels(Request $request)
{
$this->validate($request, [
'user_id' => 'required|integer',
]);
/** #var User $user */
$user = User::find($request->user_id);
return view('singleuser', ['channels' => $user->channels, 'username' => $user->name]);
}
}
In the log file no errors.
Thanks for any help and advise.
I don't think you'll receive query params as anything other than strings, so your integer validation fails.
To improve your error handling you could customize your App\Exceptions\Handler, catch your ValidationException errors with something like get_class() or instanceOf and do some neat stuff there
And of course you could not use query params at all by using Route::get('getUserChannels/{id}', 'controller#show'); and access it /getUserChannels/2 - then you could probably validate it as an integer
You could go with
Route::get('getUserChannels/{id}', ...
public function getUserChannels($id)
{
$user = User::findOrFail($id);
return view('singleuser', [
'channels' => $user->channels,
'username' => $user->name
]);
}
Then it would just throw a 404 if string, not found etc...
class ChannelController extends Controller
{
public function getUserChannels(Request $request)
{
$validator = \Validator::make($request->all(), ['user_id' => 'required|integer']);
if($validator->fails())
{
$error = $validator->errors()->first();
dd($error);
}
/** #var User $user */
$user = User::find($request->user_id);
return view('singleuser', ['channels' => $user->channels, 'username' => $user->name]);
}
}

Laravel 5 Multiple form validation rules

So i have three forms on one page. One is to change user's picture, another one is to update personal informations, and the last form is to set a new password.
My issue here is that i'm getting validation errors on the password and password confirmation fields even though i'm trying to update some information (second form).
I have created two requests:
UserEditRequest:
class UserEditRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'firstname' => 'required',
'lastname' => 'required'
];
}
}
UserUpdatePasswordRequest:
class UserUpdatePasswordRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'password' => 'required|confirmed|min:6',
'password_confirmation' => 'required|min:6',
];
}
}
within UserController updatePassword:
public function updatePassword(UserUpdatePasswordRequest $request, $id)
{
$user = User::findOrFail($id);
$user->password = bcrypt($request->get('password'));
$user->save();
return redirect()->route('user.edit',$id)->with('success','Password changed.');
}
postEdit where I handle the personal details and avatar changes:
public function postEdit(UserEditRequest $request, $id)
{
dd($request->all());
$user = User::findOrFail($id);
if($request->get('avatar'))
{
$destinationPath = public_path() . '/avatars/' . $user->id . '/';
$fileName = $user->id . '.' . $request->file('avatar')->getClientOriginalExtension();
$request->file('avatar')->move($destinationPath, $fileName);
$user->avatar = 'avatars/' . $user->id . '/' . $fileName;
$user->save();
return redirect()->route('user.edit',$id)->with('success','User avatar modified.');
}
$user->fill($request->input())->save();
return redirect()->route('user.edit',$id)->with('success','User details modified.');
}
quicky my routes:
Route::group(['prefix' => 'user', 'as' => 'user.'], function () {
Route::get('profile/{userid}', ['as' => 'edit', 'uses' => 'UserController#getEdit']);
Route::post('profile/{userid}', ['as' => 'edit', 'uses' => 'UserController#postEdit']);
Route::post('profile/{userid}', ['as' => 'updatepassword', 'uses' => 'UserController#updatePassword']);
});
});
Try to differentiate your routes for the postEdit and the updatePassword controller actions
Route::post('profile/{userid}', ['as'=>'edit', 'uses'=>'UserController#postEdit']);
Route::post('profile/password/{userid}', ['as'=>updatepassword', 'uses'=>'UserController#updatePassword']);
Using the same route for two different controller actions won't work. What I mean is how do you expect the router to determine which controller action to invoke when the form action='/profile/id' method='post' ? Hence you need to differentiate the routes.
Hope you got it.

Validation request with Laravel 5

I am trying to make validation with Laravel 5 on right way:
Here is my working code in model:
public function apiAddNewComment() {
if (Input::get("task") == 'addComment') {
$user = Auth::id();
$inputs = array(
'comment' => Input::get('comment'),
'projectID' => Input::get('projectID'),
'order' => Input::get("order"),
'level' => Input::get("level"),
);
$rules = array(
'comment' => 'required|between:15,600',
'projectID' => "required|exists:project_group,project_id,user_id,$user|numeric",
'order' => "required|numeric",
'level' => "required|numeric"
);
$validator = Validator::make($inputs, $rules);
if ($validator->fails()) {
return json_encode(array('err' => true, 'errors' => $validator->messages()->all()));
} else {
return $this->createNewComment();
}
}
}
here is my controller:
public function update($id, Comment $update)
{
return $update->apiUpdateComment();
}
How can I make validation with request?
And can someone explain me how this method works inside request:
public function authorize()
{
return false;
}
?
The Request has to basic functions: rules() and authorize()
rules returns an array that is used for the validation.
The authorize method can for example check if the user is allowed to do this request.
public function authorize() {
return Auth::check();
}
So you don't have to check it each time when you use the request in a controller.
If you need no check just return true.
UPDATE:
Generate a request File with artisan
php artisan make:request CommandRequest
then edit the generate file like this:
class CommandRequest extends FormRequest
{
public function rules()
{
return [
'comment' => 'required|between:15,600',
'projectID' => "required|exists:project_group,project_id,user_id,$user|numeric",
'order' => "required|numeric",
'level' => "required|numeric"
];
}
public function authorize()
{
return true;
}
}
Also update the controller method:
public function update($id, Comment $update, CommandRequest $request)
{
// create your comment here like:
return Comment::create($request->all());
}
You are using a Laravel 4 code I guess, you need to translate it to L5 where Input::get('var') turns into $request->input('var') for instance:
public function apiAddNewComment(Illuminate\Http\Request $request) { //Remember to add the Request as a parameter of the method
if ($request->input("task") == 'addComment') {
...
Then the validation part looks fine

Resources