Laravel 5 - redirect - laravel-5

I'am studying laravel 5 and I have an error with a route redirect.
I have a controller with two functions:
class MainController extends Controller
{
public function index() {
//Some code
return view('index.main',compact('someDatas');
}
public function update(Request $request) {
//Some code here
return redirect(route('main'));
}
}
Here is my route.php
Route::get('/', "main\MainController#index") -> name('main');
Route::get('/update', "main\MainController#update") -> name('update');
In my main.blade.php view, I have a link with a redirect to an update update route:
{{$source -> nom}}
When I click on the link, I get an error:
The page you are trying to view cannot be shown because the authenticity of the received data could not be verified.
The URL is https://127.0.0.1:8000/update, but when i remove the 's' of HTTPS I'm redirected to the main menu.
I don't understand why this error happens, I have other applications with similar code that work fine.
Thanks for your time and your responses!

This has probably nothing to do with Laravel. When you use HTTPS is tries to use a secure connection. But, you probably do not have a valid certificate for your "localhost" domain. So, you will usually get warnings. I googled your error and found the following: https://support.mozilla.org/nl/questions/1117296 It probably has something to do with your Anti Virus software.
When you use HTTP it will not try to use a secure connection and not verify de site you are connecting to. Which is the reason it works. You should use HTTP for localhost and HTTPS for production.
So again, this has nothing to do with Laravel or your code. It is something to do with HTTPS SSL and certificates. So try using HTTP instead for local development.

Try this way it's working for me.
web.php
Route::match(['get','post'],'/admin/edit_users/{id}','UsersController#EditUser');
user.blade.php
<td><a href="{{ url('/admin/edit_users',$user->id)}}">
<i class="icon icon-edit " style="font-size: 20px;color:green;"></i></a></td>
UsersController.php
public function EditUser(Request $request,$id){
$user=User::where(['id'=>$id])->first();
if($request->isMethod('post')){
$data= array('fname' =>$request->input('fname'),
'lname' =>$request->input('lname'),
'contact' =>$request->input('contact'),
);
$upatedata= DB::table('users')->where('id', $id)->update($data);
if($upatedata){
return redirect('admin/users')->with('flash_message_success','User has been update Successfully');
}else{
return redirect('admin/users')->with('flash_message_error','Incorrect User Data');
}
}
return view('admin.users.edit_user',compact('user'));
}

Related

Laravel Error 500 on a parametric route when in production

I built a small blog where a editor can create articles and post it and users can read it without login.
The issue that I'm having is the following :
In production server, if a user try to access a blog article from the home by clicking on the 'Read more' button, gets a 500 internal server error.
I'm also using other parametric routes and they are working perfectly fine.
In development server, everything works fine.
Any idea of what could the issue's cause?
Thanks in advance
In the home page I'm rendering a list of all the articles via the PublicController's index() method with the following code :
public function index()
{
$articles = Article::all();
return view('welcome', compact('articles'));
}
And it works perfectly fine.
But when a user click on a item of the list should be redirected, via the 'show()' method of the Public Controller, to the article's details page but in reality the user is getting a 500 internal server error.
The show() method :
public function show($id)
{
$article = Article::find($id);
return view('article', compact('article'));
}
One thing that can help you is to logging the exceptions in your Handler.php file. This way you can see the error details (message, file and code line).

Redirect to custom tool url in a laravel nova application

Laravel Version: 7
Nova Version: 3
PHP Version: 7.4
Database Driver & Version:
Operating System and Version: MacOS
Browser type and version: Chrome
Reproduction Repository: https://github.com/###/###
Description:
I am trying to redirect a user after checking for a condition in a middleware, I have tried to use
return redirect('/admin/paddle-subscription');
But it does not work, it just redirects the page and shows it right in the browser url but show a 404 error in the screen, it looks that as nova uses vue.js it is creating some kind of errors.
I have been reading some post in laracast https://laracasts.com/discuss/channels/nova/nova-resource-route-redirect and it is clearer to me that it requires a special way to redirect.
I have tried
return redirect()->action('\Laravel\Nova\Http\Controllers\RouterController#show', ['resource' => '/admin/paddle-subscription']);
And it does not work, how I am supposed to redirect properly?
Thanks
Detailed steps to reproduce the issue on a fresh Nova installation:
You can do this by creating the route in the backend first so that Laravel knows the page exists. Use Nova's RouterController#show action for the route like in your Laracast example and make sure to apply all the Nova middleware to it.
In app/Providers/NovaServiceProvider.php add a custom route to your routes() method:
protected function routes()
{
Nova::routes()
->withAuthenticationRoutes()
->withPasswordResetRoutes()
->register();
Route::domain(config('nova.domain', null))
->middleware(['web'])
->as('nova.')
->prefix(Nova::path())
->group(function () {
Route::get('/admin/paddle-subscription', [\Laravel\Nova\Http\Controllers\RouterController::class, 'show'])
->middleware(config('nova.middleware', []));
});
}
In your middleware you can now redirect to that route and the page will render properly:
public function handle(Request $request, Closure $next)
{
if ($foo === $bar) {
return new \Illuminate\Http\RedirectResponse('/admin/paddle-subscription');
}
return $next($request);
}
try this:
add in your nova action
public function handleRequest(\Laravel\Nova\Http\Requests\ActionRequest $request)
{
parent::handleRequest($request);
return Action::redirect('/admin/paddle-subscription');
}

Laravel Auth::id() return null after login

I have a login form to access to my web page.
In my local computer everything works fine. But now I upload my project to my server and when I login the directive #auth() is null.
I put in my controller this: dd(Auth::id()); and in my local server returns a Id but in the production server returns null...
in web.php I have tis code:
Route::group(['middleware' => 'role:admin' OR 'role:user'], function () {
Route::get('/users/inicio', function(){
dd(Auth::id());
return view('frontend.dashboardUser');});
});
This return null
Can you help me?
Thank you
I think there might be some session problem, It might not be maintaining the session state.
My suggestion:
Try echo session_id() multiple times, If every time different id is generated then there will be some problem with the session on server otherwise not.
Have you registered a new user after you pushed your code to the production? I mean have you logged in using an existing user on production? I believe your production and local Database is different and the user who exists on local does not exist on production DB.
Register a new user and login as the new user and then try accessing the route to see if you get the auth id.
For a security reason, you can't access the login user or any other session into the web.php file as well as a constructor of the class.
To archive this you can use middleware something like this:
public function __construct() {
$this->middleware(function (Request $request, $next) {
if (!\Auth::check()) {
return redirect('/login');
}
$this->userId = \Auth::id(); // you can access user id here
return $next($request);
});
}
This link can help you more. Good luck!!!

Testing redirect links to external sites

I have a link on a page /my/example/page which links to a laravel route my.route.
Route
Route::group(['middleware' => ['auth']], function () {
Route::group(['middleware' => ['Some\Custom\Auth\Middleware:1']], function () {
Route::match(['GET', 'POST'], '/my/route/to/external/controller', 'exampleController#externalLink')->name('my.route');
}
}
Link on /my/example/page
Link
This route /my/route/to/external/controller points to this controller method externalLink in the exampleController controller, which returns the url for the href to use
public function externalLink()
{
return $this->redirect->away('www.externalsite.com');
}
My test is
$this->visit(/my/example/page)
->click('Link')
->assertRedirectedToRoute('my.route');
I constantly get the error
Symfony\Component\HttpKernel\Exception\NotFoundHttpException
when I use the click() testing method.
I can catch this using #expectedException but his doesn't help as I am expecting to see a different page.
I have also tried (not together);
->assertResponseStatus(200);
->seePageIs('www.externalsite.com');
->assertRedirect();
->followRedirects();
From browser inspection, when the url is clicked I get
http://www.example.com/my/route/to/external 302
http://www.externalsite.com 200
How can I functionally test the button being clicked and redirecting to an external site?
I am struggling with a similar problem right now, and I have just about given up on testing the endpoint directly. Opting for a solution like this...
Test that the link contains proper information in the view:
$this->visit('/my/example/page')
->seeElement('a', ['href' => route('my.route')]);
Moving the logic in the controller to something you can test directly. The Laravel\Socialite package has some interesting tests that might be helpful if you do this...
class ExternalLinkRedirect {
public function __construct($request){
$this->request = $request;
}
public function redirect()
{
return redirect()->away('exteranlsite.com');
}
}
Then test it directly
$route = route('my.route');
$request = \Illuminate\Http\Request::create($route);
$redirector = new ExternalLinkRedirect($request);
$response = $redirector->redirect();
$this->assertEquals('www.externalsite.com', $response->getTargetUrl());
A simple way is to use the get method instead of visit.
An example:
$this->get('/facebook')
->assertRedirectedTo('https://www.facebook.com/Les-Teachers-du-NET-516952535045054');

Laravel 5 and Socialite - New Redirect After Login

Another newb question here, but hopefully someone can shed some light:
I am using Socialite with Laravel 5, and I want to be able to redirect the user to a page on the site after they have logged in. The problem is that using
return redirect('any-path-I-put-here');
simply redirects back to 'social-site/login?code=afkjadfkjdslkfjdlkfj...' (where 'social-site' is whatever site is being used i.e. facebook, twitter, google, etc.)
So, what appears to me to be happening is that the redirect() function in the Socialite/Contracts/Provider interface is overriding any redirect that I attempt after the fact.
Just for clarification, my routes are set up properly. I have tried every version of 'redirect' you can imagine ('to', 'back', 'intended', Redirect::, etc.), and the method is being called from my Auth Controller (though I have tried it elsewhere as well).
The question is, how do I override that redirect() once I am done storing and logging in the user with socialite? Any help is appreciated! Thank you in advance.
The code that contains the redirect in question is:
public function socialRedirect( $route, $status, $greeting, $user )
{
$this->auth->login( $user, true );
if( $status == 'new_user' ) {
// This is a new member. Make sure they see the welcome modal on redirect
\Session::flash( 'new_registration', true );
return redirect()->to( $route );// This is just the most recent attempt. It originated with return redirect($route);, and has been attempted every other way you can imagine as well (as mentioned above). Hardcoding (i.e., 'home') returns the exact same result. The socialite redirect always overrides anything that is put here.
}
else {
return redirect()->to( $route )->with( [ 'greeting' => $greeting ] );
}
}
... The SocialAuth class that runs before this, however, is about 500 lines long, as it has to determine if the user exists, register new users if necessary, show forms for different scenarios, etc. Meanwhile, here is the function that sends the information through from the Social Auth class:
private function socialLogin( $socialUser, $goto, $provider, $status, $controller )
{
if( is_null( $goto ) ) {
$goto = 'backlot/' . $socialUser->profile->custom_url;
}
if( $status == 'new_user' ) {
return $controller->socialRedirect($goto, $status, null, $socialUser);
}
else {
// This is an existing member. Show them the welcome back status message.
$message = 'You have successfully logged in with your ' .
ucfirst( $provider ) . ' credentials.';
$greeting =
flash()->success( 'Welcome back, ' . $socialUser->username . '. ' . $message );
return $controller->socialRedirect($goto, $status, $greeting, $socialUser);
}
}
I managed to workaround this problem, but I am unsure if this is the best way to fix it. Similar to what is stated in question, I got authenticated callback from the social media, but I was unable to redirect current response to another url.
Based on the callback request params, I was able to create and authenticate the user within my Laravel app. It worked good so far but the problems occured after this step when I tried to do a return redirect()->route('dashboard');. I tried all the flavours of redirect() helper and Redirect facade but nothing helped.
The blank page just stared at my face for over 2 days, before I checked this question. The behaviour was very similar. I got redirect from social-media to my app but could not further redirect in the same response cycle.
At this moment (when the callback was recieved by the app and user was authenticated), if I refreshed the page manually (F5), I got redirected to the intended page. My interpretation is similar to what's stated in this question earlier. The redirect from social-media callback was dominating the redirects I was triggering in my controller (May be redirect within Laravel app got suppressed because the redirect from social-media was still not complete). It's just my interpretation. Experts can throw more light if they think otherwise or have a better explaination.
To fix this I issued a raw http redirect using header("Location /dashboard"); and applied auth middleware to this route. This way I could mock the refresh functionality ,redirect to dashboard (or intended url) and check for authentication in my DashboardController.
Once again, this is not a perfect solution and I am investigating the actual root of the problem, but this might help you to move ahead if you are facing similar problem.
I believe you are overthinking this. Using Socialite is pretty straight forward:
Set up config/services.php. For facebook I have this:
'facebook' => [
'client_id' => 'your_fb_id',
'client_secret' => 'your_fb_secret',
'redirect' => '>ABSOLUTE< url to redirect after login', //like: 'http://stuff'
],
Then set up two routes, one for login and one for callback (after login).
In the login controller method:
return \Socialize::with('facebook')->redirect();
Then in the callback function
$fb_user = \Socialize::with('facebook')->user();
// check if user exists, create it and whatnot
//dd($fb_user);
return redirect()->route('some.route');
It should be pretty much similar for all other providers.
We are using the Socialite login in our UserController as a trait. We simply overrode the AuthenticatesSocialiteLogin::loginSuccess() in our controller.
use Broco\SocialiteLogin\Auth\AuthenticatesSocialiteLogin;
class UserController extends BaseController
{
use AuthenticatesSocialiteLogin;
public function loginSuccess($user)
{
return redirect()->intended(url('/#login-success'));
}
....

Resources