Laravel 5.4 HTTP Testing - laravel-5

I am writing a test for a json route in laravel 5.4, I am supposed to be redirected if the GET request is not ajax, the code works correctly on the browser chrome but when I test it does not work as expected. I tried different variation to add headers to the request none worked.
When I changed the request to POST it worked as excepted, I am not sure what I am missing. here is the code
routes.php
// Redirect all none-ajax routes to the main edit test route
if (!Request::ajax()) {
Route::get('{vue?}', ['as'=>'vue_redirect', 'uses' => 'TestController#vueHandler'])->where('vue', '[\/\w\.-]*');
}
/*
* General route to the test instructions
*/
Route::get('getInstructions', ['as' => 'getInstructions', 'uses' => 'TestController#getInstructions']);
This is the test code
public function testgetTest()
{
$x = $this->actingAs($this->customer)->json('GET', '/test/edit/' . $this->test->id . '/getInstructions');
var_dump($x->getContent());
}
I tried variation like
$this->actingAs($this->customer)->call('GET', '/test/edit/' . $this->test->id . '/getInstructions', [], [], ['X-Requested-With' => 'XMLHttpRequest']
Put also did not work.
When I change to POST and print out the headers this is what I get
if (!Request::ajax()) {
var_dump(Request::header());
Route::get('{vue?}', ['as'=>'vue_redirect', 'uses' => 'TestController#vueHandler'])->where('vue', '[\/\w\.-]*');
}
/*
* General route to the test instructions
*/
Route::post('getInstructions', ['as' => 'getInstructions', 'uses' => 'TestController#getInstructions']);
Output for the POST working
array(5) {
["host"]=>
array(1) {
[0]=>
string(7) "app.dev"
}
["user-agent"]=>
array(1) {
[0]=>
string(11) "Symfony/3.X"
}
["accept"]=>
array(1) {
[0]=>
string(63) "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}
["accept-language"]=>
array(1) {
[0]=>
string(14) "en-us,en;q=0.5"
}
["accept-charset"]=>
array(1) {
[0]=>
string(30) "ISO-8859-1,utf-8;q=0.7,*;q=0.7"
}
}
string(373) "{"success":true,"message":{"id":1,"type_id":"2","user_id":"3","test_name":"Test-MEAjT","test_url":"http:\/\/www.kuphal.com\/eveniet-distinctio-voluptas-sint","test_instructions":"Accusamus laboriosam alias magni ea. Et libero totam sunt ut.","status":"draft","completion_date":null,"is_onboarding":"0","created_at":"2017-04-02 19:50:00","updated_at":"2017-04-02 19:50:00"}}"
I can see the correct output, but the headers are not correct which is confusing for me.

I managed to solve this issue based on guidance of #sisve #lagbox I made the following updates to the code.
I removed the condition of checking ajax to a middleware, then I moved the location of the route vue_redirect to the bottom of the match so it does not conflict with other routes. (which was a bug that redirect all the traffic to the wrong route).
Routes.php
Route::group(['middleware' => ['VerifyAjaxRequest']], function(){
/*
* General route to the test instructions
*/
Route::get('getInstructions', ['as' => 'getInstructions', 'uses' => 'TestController#getInstructions']);
});
VerifyAjaxRequest.php middleware
public function handle($request, Closure $next)
{
// Redirect all none-ajax routes to the main edit test route
if (!$request->ajax()) {
return redirect(route('vue_redirect'));
}
return $next($request);
}
Test.php
public function testgetTest()
{
$response = $this->actingAs($this->customer)->json('get', '/test/edit/' . $this->test->id . '/getInstructions', [], ['X-Requested-With'=>'XMLHttpRequest']);
var_dump($response->getContent());
}
Now it works as excepted including headers and correct response

Related

InertiaJs Redirect returns 302 but doesn't render

Really sorry if this has been covered before but I can't find a working solution and have even asked numerous work colleagues.
I have a form which sends a POST request to my MailController, validation and everything works just as expected, but on success, I want to redirect to a Thank you page. The Post request returns either a 200 or 302 depending on the method I try but every time it only sends the HTML to the response and doesn't render the component.
I can, however, navigate to that page if I visit the URL and it loads perfectly.
I've tried
to_route
Inertia::render
Redirect()
Redirect()->route()
Redirect::route()
even sending it in response, catching it in Axio's request in the component, and redirecting from there.
This is driving me nuts I just can't see what I'm doing wrong.
TIA for your help and suggestions
//controller
<?php
namespace App\Http\Controllers;
use ...
use Inertia\Inertia;
use...
class MailController extends Controller
{
public function sendEmail(Request $request)
{
$contact = $request->validate([
......
],[
.......
]);
Mail::to('email#email.co.uk')->send(new ContactEmail($contact));
return Redirect::route('thankyou');
// return response()->json([
// 'data' => $contact,
// 'message' => 'Message sent successfully.',
// 'redirect' => route('thankyou')
// ], 201);
}
}
// route
Route::get('/thankyou', function () {
return Inertia::render('Thankyou');
})->name('thankyou');
// submit function
submitContact: function () {
axios.post('/email', this.contact)
.then(response => {
console.log(response.data.redirect);
// if (response.data.redirect) {
// return Inertia.location(response.data.redirect);
// }
}).catch(err => {
const errors = err.response.data.errors;
if (err) {
Object.keys(errors).forEach(key => {
this.errors[key] = errors[key][0];
});
}
})
}

Laravel: Redirect back missing url and return 404 page

I have a problem with redirect back in laravel 8.
When I access page url like: localhost:8000 and change languages from english to japan. Browser back to localhost:8000 and update new selected language. But when I access dynamic url like localhost:8000/post/tin-tuc/recruiment and select language. Browser back to url like this localhost:8000/post/tin-tuc/language/ja and show 404 page error. Tks for your help.
Here is my code:
Web.php
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('post/{category_slug}/{content_slug}', [App\Http\Controllers\PostController::class, 'detail'])->name('post');
Route::get('post-detail/{content_slug}/{post_slug}', [App\Http\Controllers\PostDetailController::class, 'detail'])->name('post.detail');
Route::get('language/{locale}', function ($locale) {
app()->setLocale($locale);
session()->put('locale', $locale);
return Redirect::intended('/');
});
Localization middleware
public function handle(Request $request, Closure $next)
{
if (Session::has('locale')) {
App::setLocale(Session::get('locale'));
}
return $next($request);
}
config/app.php
'locale' => 'en',
'fallback_locale' => 'en',
'available_locales' => [
'English' => 'en',
//'Vietnamese' => 'vi',
'Japanese' => 'ja',
],
app/http/Provider/AppServiceProvider
public function boot()
{
view()->composer('partials.language_switcher', function ($view) {
$view->with('current_locale', app()->getLocale());
$view->with('available_locales', config('app.available_locales'));
});
$categoriesGeneral = Category::where('status', config('constants.status.Alive'))->get();
view()->share('categoriesGeneral', $categoriesGeneral);
$contentItems = Content::join('categories', 'contents.category_id', '=', 'categories.id')
->where('contents.status', config('constants.status.Alive'))
->where('categories.status', config('constants.status.Alive'))
->select('contents.*', 'categories.category_name', 'categories.slug AS category_slug')
->get();
view()->share('contentItems', $contentItems);
}

Missing required parameters for [Route: admin::sliders.index] [URI: admin/slider-groups

In my laravel application whenever I go to this route: admin/slider-groups I get the following error message:
We have following routes.
/slider-groups
/slider-groups/1
/slider-groups/1/sliders/create
/slider-groups/1/sliders/10/edit
blade.php
<a href="{{ route('admin::sliders.index') }}" class="mr-1">
web.php
Route::group([
'prefix' => 'admin',
'as' => 'admin::',
], function() {
Route::resource('slider-groups', 'Admin\SliderGroupController');
Route::prefix('slider-groups/{sliderGroup}')->group(function(){
Route::resource('sliders', 'Admin\SliderController');
});
});
SliderGroupController.php
public function index(Request $request)
{
if ($request->search) {
$sliderGroups = SliderGroup::search($request->search)->paginate(30);
} else {
$sliderGroups = SliderGroup::paginate(30);
}
if ($sliderGroups->count() == 0 && $request->search ) {
msg()->warning('دقت کنید', 'هیچ رکوردی یافت نشد.');
}
return view('slider::admin.groups.index', compact('sliderGroups'));
}
To note I'm not including all the html code of index.blade.php as it's too long the only blade code is from what i have pasted.
Since you are prefixing siderGroup, you need to pass the $sliderGroup->id to each route in
Route::resource('sliders', 'Admin\SliderController');
For example do:
Link
instead of:
Link

Laravel doesn't get data from Postman

I am starting work on an API in Laravel, using Postman. However, no matter what I send via Postman, the $request received is empty.
Route in Laravel:
Route::group(['namespace' => 'Api', 'as' => 'api.'], function() {
Route::post('/stock-list', 'DataController#stock_list');
});
Controller method:
public function stock_list(Request $request)
{
logger()->info($request->all());
return response()->json([
'request' => $request
]);
}
The log shows that $request->all() is an empty array. Since I am also returning $request to Postman as a test, this is what Postman gets as a response:
{
"request": {
"attributes": {},
"request": {},
"query": {},
"server": {},
"files": {},
"cookies": {},
"headers": {}
}
}
What am I sending? In Postman, I have this content in the body tab:
{
'foo' : 'bar'
}
The body type is selected as raw and Postman reads it as JSON.
In terms of authentication, I have chosen basic auth with username and password for now, however I have not done anything on the Laravel side about this (as you can see from the route and controller). As far as I can tell, this shouldn't matter at this point - the request should still be received by Laravel correctly, then either an "unauthenticated" response should be returned, or no authentication should happen at all since there is no auth middleware on the route.
Can someone explain the cause of the problem and suggest a solution?
EDIT
Here are the headers in Postman:
{
'foo' : 'bar'
}
is not a valid JSON. By standard you have to use double quotes.
{
"foo" : "bar"
}
You already set content-type to json which is good. I believe it should be working now.
I did not understand why you used logger()->info($request->all()); in your code but I tried your code like bellow and it worked
route:
Route::group(['prefix' => 'Api'], function() {
Route::post('stock-list', 'Api\UsersControllers#stock_list');
});
controller:
public function stock_list(Request $request)
{
$request=$request->all();
return response()->json([
'request' => $request
]);
}
postmans:

Router redirecting to the another page

I have route like
Route::get('admin/selfcontacteditdata','SelfcontectController#edit')->name('selfcontectedit');
Route::post('admin/selfcontactupdatedata','SelfcontectController#update')->name('selfcontectupdate');
If i just go to my browser and right admin/selfcontacteditdata it redirect me to
admin/newsshowdata
And my index function is
public function __construct()
{
return $this->middleware('auth');
}
public function index()
{
request()->validate([
'email' => 'required',
'mobileno' => 'required',
'facebook'=>'required',
'google'=>'required',
'map'=>'required',
]);
$data = selfcontect::find(1);
return view('/admin/selfcontectedit',compact('data'));
}
And my middleware is
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}
My rest admin routes are working fine.
I had the same problem but I was writing table name wrong and my file was not saved as .blade please check are you also doing the same thing and there is no meaning of validation in edit function your edit function must be like
public function edit()
{
$data = selfcontect::find(1);
return view('/admin/selfcontectedit',compact('data'));
}
and your function name should be edit
You should use Accept key not Content/type
You can't redirect through view, actually your are calling view.
Correct syntax is
return view('view_name',compact('data'));
If you want to redirect to any route you have to call like this
return redirect()->to('admin/selfcontacteditdata');
Redirect to a Route
If in your routes.php file you have a route with a name, you can redirect a user to this particular route, whatever its URL is:
app/Http/routes.php:
get('books', ['as' => 'books_list', 'uses' => 'BooksController#index']);
app/Http/Controllers/SomeController.php
return redirect()->route('books');
This is really useful if in the future you want to change the URL structure – all you would need to change is routes.php (for example, get(‘books’, … to get(‘books_list’, …), and all the redirects would refer to that route and therefore would change automatically.
And you can also use parameters for the routes, if you have any:
app/Http/routes.php:
get('book/{id}', ['as' => 'book_view', 'uses' => 'BooksController#show']);
app/Http/Controllers/SomeController.php
return redirect()->route('book_view', 1);
In case of more parameters – you can use an array:
app/Http/routes.php:
get('book/{category}/{id}', ['as' => 'book_view', 'uses' =>
'BooksController#show']);
app/Http/Controllers/SomeController.php
return redirect()->route('book_view', [513, 1]);
Or you can specify names of the parameters:
return redirect()->route('book_view', ['category'=>513, 'id'=>1]);

Resources