Laravel 5.4 redirect / not working - laravel-5.4

The command:
php artisan route:list
shows:
GET|HEAD | / | App\Http\Controllers\StaticController#index
I added following code in my StaticController controller
public function logout(Request $request)
{
Auth::logout();
$request->session()->flush();
return Redirect::route('/');
}
In my web.php:
Route::get('/', 'StaticController#index');
Route::group(['middleware' => ['web', 'auth']], function () {
Route::get('/logout', 'MiscController#logout');
});
When I click on logout link, it shows the message:
InvalidArgumentException in UrlGenerator.php line 304:
Route [/] not defined.
When I reload the page showing error, it redirects me to: /login
Not able to figure out what's wrong here.

Replace
return Redirect::route('/');
with
return redirect('/');
Think there is no route with name /
But if you prefer to use route names when redirecting, you may do this:
return redirect()->route('your.route.name', ['id' => $order->id]);

Related

How to route a url to include scrolling down to a div id in Laravel

I am validating a contact form. I wrapped it in a div with the id of "contactform". When validation messages appear after submission I want the redirected page to scroll down automatically to the "contactform" div so users don't have to scroll down themselves to correct the form.
I can accomplish this easily by manually typing the url:localhost:8000/#contactform
However I cannot get the routing to work in Laravel.
I tried altering the controller to:
return Redirect::to('/#contactform');
I tried:
return Redirect::to('#contactform');
return Redirect::to('/' . '#contactform');
return view('/')->with('#contactform');
return view('/#contactform');
return view('/pages.index.#contactform');
return view('/pages.index#contactform');
They all return without the #contactform in the url.
I know there is a javascript way to accomplish this, but I was really trying to stay away from javascript for now. There has to be a simpler way I just cannot see it. I'm new to Laravel and completely self-taught. Thanks
***EDIT
I tried a new controller step by step. Without validation it works. Validation seems to break it.
This works:
public function store() {
return (string) Redirect::to('/#contactform');
}
This breaks it:
public function store(Request $request) {
$this->validate($request, [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email',
'telephone' => 'nullable',
'comments' => 'required',
]);
return (string) Redirect::to('/#contactform');
}
The top of the controller page I call the request and redirect like this:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
Can anyone help me get down to the reason why I cannot validate without breaking the url route?
On validation failure it will cause a redirect 'back'. It is entirely possible that 'back' is the same URI you want to redirect to, so from your perspective it looks like it is redirecting wrong when it is correct. If you remove the validation you should get the correct redirect.
Side note: On the server side the hash is not part of the URL. It is a client side thing.
A solution that works for me is to compact() a Boolean variable through the controller.
Link example
Passing the variable to the controller
Route::get('/post={post_id}+{scroll}',[PostController::class, 'show']);
If the variable equals 'scroll' then switch the boolean variable to true
public function show($post_id, $scroll){
if($scroll == 'scroll'){
$scroll = true;
}else{
$scroll = false;
}
return view('yourview', compact('scroll'))
}
Run the script if $scroll is true
<script>
#if($scroll)
$(document).ready(function () {
$('html,body').animate({ scrollTop: 99999 }, 'slow');
});
#endif
</script>

Trying to add User in Laravel using Angular but it shows me an error

I'm trying to use the post method to pass the user to Laravel using a form in HTML so I can store the user in the UserController into the database. I get an CSRF Token mismatch error.
I have used this Method to store the user:
addUser(user: User):Observable<User>{
return this.http.post<User>(this.apiURL+'/addUser',user, httpOptions);
}
When I console.log the user it works fine. It shows me all attributes when I klick on submit.
I have use this Route in Laravel to store the user:
Route::post('/addUser','UserController#create');
In the Controllermethod I used this code:
public function create(Request $request)
{
$data2 = $request->json()->all();
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
}
Laravel, by default, has VerifyCsrfToken middleware enabled for all routes. This is for security (to avoid cross site attacks) and checks for a CSRF token for all requests. But you can set middlewares for route groups such as web, api',console`.
Try to move VerifyCsrfToken middleware from $middleware variable to web group in $middlewareGroups variable in Http/Kernel.php. By doing this, you only enable this middleware for web routes.
Hope this helps.

Yii2 Functional test send ajax get request not working

I am trying to test an ajax request with a basic install of Yii2. I am just using the SiteController::actionAbout() method to try this out.
public function actionAbout()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'message' => 'hello world',
'code' => 100,
];
}
And in the test:
public function sendAjax(\FunctionalTester $I)
{
$I->sendAjaxGetRequest('site/about');
$r = $I->grabResponse();
die(var_dump($r));
}
The grab response method is one I wrote myself in a \Helper\Functional.php file:
public function grabResponse()
{
return $this->getModule('Yii2')->_getResponseContent();
}
When I dump out the response, I just see the html from the site/index page.
This happens for any route except the site default. If I try to do the same thing using site/index then it returns:
string(36) "{"message":"hello world","code":100}"
What am I missing / doing wrong?
Note the difference between a Yii route and the actual URL.
The argument to sendAjaxGetRequest() is the URL, not the route (at least if you pass it as a string, see below).
Dependent on your UrlManager config you might have URLs like /index.php?r=site/about, where the route is site/about. You can use the Url helper of Yii to create the URL:
$I->sendAjaxGetRequest(\yii\helpers\Url::to(['site/about']));
I am not sure about this but if you have the Codeception Yii2 module installed you should also be able to pass the route like this:
$I->sendAjaxGetRequest(['site/about']);

Component not rendered when calling "replace" in onEnter

I am trying to implement simple authentication with react-router. I think there is an issue with replace and callback. Consider following code:
1) Routing configuration
function getRoutes() {
return {
path: "/",
indexRoute: require("./Home"),
component: require("./Shared/Layout"),
onEnter: handleEnter,
childRoutes: [
require("./Login"),
require("./Secured"),
require("./Any")
]
}
}
function handleEnter(nextState, replace, callback) {
let state = store.getState()
if (!state.hasIn(["shared", "user"])) {
store.dispatch(fetchUser())
.then(callback)
}
}
2) ./Secured route configuration
export = {
path: "/secured",
component: require("./Secured"),
onEnter(nextState, replace) {
let state = store.getState()
if (!state.getIn(["shared", "user"])) {
replace("/login")
}
}
}
It should work like this:
Fetch user when entering root route (async operation, we need callback)
Go to /secured and check whether user is authenticated when entering the route
If user is not authenticated go to /login
The problem is that the /login page will not be rendered. The URL is changed to /login, but nothing is displayed and there are no error messages in console. When I remove callback parameter from the root route configuration, it starts working as expected.
Am I doing something wrong?
Well, it was really stupid :) I've forgot to call callback when user is already authenticated.

cakephp 3.x _serialize key not working

I an trying to return json from a cakephp 3.1 controller function. My problem is that no matter what I do with the _serialize flag, the response is always that there is a missing view template file.
In the cake docs it says to set the _serialize flag if you do not need to use a template to format the response. Cake Docs on View _serialize
Below is the Javascript on the client side that initializes the process
function save_activity( mod, act, resp ) {
$.ajax({
method: 'POST',
url: '/activities/saveActivity',
data: {
'module' : "example1",
'activity_name' : "example2",
'response' : "example3"
},
dataType: 'json',
error: function( xhr, status, error ){
alert( status + error );
},
success: function( data, status, xhr ){
alert( status + data.success );
}
});
}
The Controller code that handles the json from the client.
public function saveActivity()
{
$user = $this->Auth->user();
//This line does not seem to do anything
//$this->request->input('json_decode', 'true');
//Debugger::log($this->request->data);
$activityTable = TableRegistry::get('Activities');
$activity = $activityTable->newEntity();
$activity->user_id = $user['id'];
$activity->module = $this->request->data('module');
$activity->activity_name = $this->request->data('activity_name');
$activity->response = $this->request->data('response');
//These lines do not have any effect
//$this->RequestHandler->renderAs($this, 'json');
//$this->response->type('application/json');
//$this->viewBuilder()->layout(null);
//$this->render(false);
$msg = '';
if ($activityTable->save($activity)) {
$msg = 'Activity Stored';
} else {
$msg = 'Activity Not Stored';
}
$this->set(['response' => $msg]);
//comment or uncomment this line and it makes no difference
//as it still returns a json response about a missing template.
$this->set('_serialize', true);
}
The error message I get when I include or remove the _serialize flag.
"Template file "Pages\json\module1\activity4.ctp" is missing."
Anyone have any insight into this mechanims? The workaround I have found is to include the template file... but this means I will have to generate a few dozen essentially empty template files to handle all the places this call is generated from.
Any help please?
Problem cause:- Violation of assumption.
My assumption was that the saveActivity method was being executed. While the reality was that AuthComponent was failing to allow access to that method and the default handler was being run instead, then the default view template was being looked for... and failing.
I found this by looking at the stack track attached to the error message in the returned page via devTools. I should also have verified this assumption with some simple trace logging calls. I already had the clue when I commented out the "$this->set('_serialize', true);" and nothing changed.
Then the simple solution was to authorise the method in the controllers beforeFilter:
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$this->Auth->allow('saveActivity');
$this->Auth->allow('getActivity');
$this->eventManager()->off($this->Csrf);
}
Thanks for the assist ndm.