getting intended target url without losing the values in middleware - php

I have the following two settings page routes one for normal settings and the other for secured and admin related settings which uses the same middleware "password.confirm"
Route::get('/admin/settings',WebsiteInfoController::class,'edit'])->name('settings')->middleware('password.confirm');
Route::get('/settings',[WebsiteInfoController::class, edit'])->name('user.settings')->middleware('password.confirm');
This middleware redirects me to a second page where I have to enter password and then only i can get access to my intended page.
In my middleware I have the following function. I want to make an additional check if the user is intending to access the admin related settings
public function store(Request $request)
{
$this->validate($request, [
'secret_password' => ['sometimes','required'],
'password' => ['required','password:web'],
]);
if(redirect()->intended()->getTargetUrl()==route('settings')){
$secret_password =WebsiteInfo::first()->secret_password;
if (!Hash::check($request->secret_password, $secret_password)) {
throw ValidationException::withMessages([
'secret_password' => __('auth.password'),
]);
}
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended(RouteServiceProvider::HOME);
});
});
}
Everything works fine in this method but the intended URL is lost when all the check is performed and I am redirected to homepage instead of settings page. I also tried to save the URL in a variable and use it later in the redirect command like
$path=redirect()->intended()->getTargetUrl();
if($path==route('settings')){
$secret_password =WebsiteInfo::first()->secret_password;
if (!Hash::check($request->secret_password, $secret_password)) {
throw ValidationException::withMessages([
'secret_password' => __('auth.password'),
]);
}
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended($path);
This method works fine but it also loses the URL if the second validation fails and the user is redirected back to the confirm password page. Now when I try to perform the validation second time it again loses the intended URL and redirects me back to home page.
i also tried the check with $request method.
if($request->route()->named('settings')){
$secret_password =WebsiteInfo::first()->secret_password;
if (!Hash::check($request->secret_password, $secret_password)) {
throw ValidationException::withMessages([
'secret_password' => __('auth.password'),
]);
}
}
This method however, is not able to detect the route in middleware and the validation check is not at all performed.
So, My question is how do i check for the intended URL and perform validation check without losing the intended URL even after multiple failed validation attempts?

Your method is all fine. You just used the wrong method to extract the target website URL. It is true that redirect()->intended()->getTargetUrl() gives you the target page URL but it also removes the target website URL from the session so when you finish performing the checks and want to redirect to the intended page there is no intended page URL found in the session and you get redirected to the default fall back URL. This is what the redirect function does
public function intended($default = '/', $status = 302, $headers = [], $secure = null) {
$path = $this->session->pull('url.intended', $default);
return $this->to($path, $status, $headers, $secure);
}
Here, the $request->route()->named('settings) method does not work since you are not directly interacting with your initial view but instead through a middleware view which does not send the intended page request.
Use the following code and I guess you will be all fine with your validation attempts. It will work even after multiple failed login attempts.
public function store(Request $request) {
$this->validate($request, [
'secret_password' => ['sometimes','required'],
'password' => ['required','password:web'],
]);
$path=session()->get('url.intended', RouteServiceProvider::HOME);
if($path==route('settings')) {
$secret_password =WebsiteInfo::first()->secret_password;
if (!Hash::check($request->secret_password, $secret_password)) {
throw ValidationException::withMessages([
'secret_password' => __('auth.password'),
]);
}
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended($path);
}

Related

Laravel testing. Get rout autoredirects from "/signin" to "am/signin", when for post I need to manually write "am/signin". Why post acts like this?

I use Laravel 9, but it is updated version. I mean, the project was written in laravel 5.4 and updated it to 9 later.
Here's my routes
Route::group(['middleware' => 'locale', 'prefix' => '{locale?}'], function () {
Route::get('/signin', 'Front\UsersController#getSignin');
Route::post('/signin', 'Front\UsersController#postSignin');
});
Here's my tests
public function test_get_signin(){
$response = $this->get('/signin');
$response->assertStatus(302);
}
public function test_post_signin(){
$response = $this->post('am/signin');
$response->assertStatus(302);
}
It works well when I do $this->post('am/signin');
But it is not correct. By the idea it must work when I write $this->post('/signin') without manually adding what should be added automatically. But in fact I get status code 405.
UsersController method for post('/signin) route.
public function postSignin($lang, Request $request){
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
if (Auth::validate(['email' => $request['email'],'password' => $request['password']])
|| Auth::validate(['username' => $request['email'],'password' => $request['password']])) {
$verify = User::where(['email'=> $request['email']])->first();
$verify = $verify?$verify:User::where(['username'=> $request['email']])->first();
if($verify->status =='blocked'){
if ($request->expectsJson()) {
return response()->json(array('verify'=> trans('email.profile-block')), 422);
}
}elseif(!$verify->verified){
return response()->json(array('verify'=> trans('validation.active_account').' '
.trans('car.click').' <a class="resend-link" href="/'.$lang.'/resendtoken/'.$verify->email_token
.'">'.trans('car.here1').'</a> '.trans('validation.resend_link')), 422);
}elseif($verify->status =='pending'){
return response()->json(array('verify'=> trans('car.company_napp')), 422);
}elseif($verify->status =='active'){
if(filter_var($request->email, FILTER_VALIDATE_EMAIL)){
$field = 'email';
}else{
$field = 'username';
}
if (Auth::attempt([$field => $request->email, 'password'=>$request->password],$request->remember)) {
UserLoginInfo::create(['user_id'=>Auth::id(),'ip_address'=> $request->ip(),
'info'=>json_encode(self::get_user_info())]);
if ($request->remember) {
User::where('id', Auth::id())->update(array('signed_in_for_remember_me' => Carbon::now()));
}
return Auth::user()->balance;
}
}
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
$this->incrementLoginAttempts($request);
return $this->sendFailedLoginResponse($request);
}
more short:
$this->get('/signin'); gives status code 302
$this->post('am/signin'); gives status code 302
$this->post('/signin'); gives status code 405
I tried
to use withoutMiddleware() - no positive result.
public function test_get_signin(){
$response = $this->withoutMiddleware('locale')->get('/signin');
$response->assertStatus(302);
}
public function test_post_signin(){
$response = $this->withoutMiddleware('locale')->post('/signin');
$response->assertStatus(302);
}
removed "?" symbol from 'prefix' => '{locale?}' in route group - no use.
commented the : Route::get('/signin', 'Front\UsersController#getSignin'); - no use again.
instead of withoutMiddleware('locale') I also used just a withoutMiddleware() - no use again.
IMPORTANT!
Both routes work well when testing with browser. I mean. User can enter his signin page and also successfully be signed in.
What's going on? How can I force post to work automatically with "/signin"? It's also weird, if I manually have to write "am/" then why it returns 302 instead of 200?
Update
I created a new project and tried to experiment there with route group and get, post methods.
Here's the routes
Route::group(['middleware' => 'locale', 'prefix' => '{locale?}'], function () {
Route::get('/test', function () {
return view('welcome');
});
Route::post('/test', function () {
return view('welcome');
});
});
here's the tests
public function test_1()
{
$response = $this->get('/test');
$response->assertStatus(200);
}
public function test_2()
{
$response = $this->post('/test');
$response->assertStatus(200);
}
test1 and test2, both of them return status 404
And when I use tests like this, I mean, adding a prefix manually
public function test_1()
{
$response = $this->get('/am/test');
$response->assertStatus(200);
}
public function test_2()
{
$response = $this->post('/am/test');
$response->assertStatus(200);
}
both of them return 200
This is good, very good. But why in my situation of my current project I get for get method 200 instead of 404 and for post 405 instead of 404, I don't have an idea. The interesting fact. I commented the whole exceptions Handler.php's code and no use. The get method everytime returns 200 when it must return 404.
Update 2
I've got some new interesting info from my experiments. If in my current project I want to test get method with uri "/signin" without '/am' part with $this->withoutMiddleware(); then I get 500, but without $this->withoutMiddleware(); I get 200
And to know what 500 want to say I used $response->dd(); and got this result
Spatie\LaravelIgnition\Exceptions\ViewException: Undefined variable
$errors in file
C:\xampp\htdocs\dashboard\test\hayvcar\storage\framework\views\7ced869fcb986989ef0f5838d6567d1b5fa4f895.php
on line 1
And if use $this->withoutExceptionHandling(); instead of $response->dd();
We'll get this result
Illuminate\View\ViewException : Undefined variable $errors (View: C:\xampp\htdocs\dashboard\test\hayvcar\resources\views\front\transport\index.blade.php)
C:\xampp\htdocs\dashboard\test\hayvcar\storage\framework\views\7ced869fcb986989ef0f5838d6567d1b5fa4f895.php:1
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\Engines\PhpEngine.php:60
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\Engines\CompilerEngine.php:61
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:139
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:122
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:91
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Http\Response.php:69
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Http\Response.php:35
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:833
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:802
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:725
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:141
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:116
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:726
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:703
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:667
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:656
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:167
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:141
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:116
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:142
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:111
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:526
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:293
C:\xampp\htdocs\dashboard\test\hayvcar\tests\Feature\RoutesTesting.php:1718
Caused by
ErrorException: Undefined variable $errors
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Bootstrap\HandleExceptions.php:255
C:\xampp\htdocs\dashboard\test\hayvcar\storage\framework\views\7ced869fcb986989ef0f5838d6567d1b5fa4f895.php:1
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php:107
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Filesystem\Filesystem.php:108
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\Engines\PhpEngine.php:58
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\Engines\CompilerEngine.php:61
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:139
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:122
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\View\View.php:91
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Http\Response.php:69
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Http\Response.php:35
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:833
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:802
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:725
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:141
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:116
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:726
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:703
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:667
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Routing\Router.php:656
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:167
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:141
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php:116
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:142
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php:111
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:526
C:\xampp\htdocs\dashboard\test\hayvcar\vendor\laravel\framework\src\Illuminate\Foundation\Testing\Concerns\MakesHttpRequests.php:293
C:\xampp\htdocs\dashboard\test\hayvcar\tests\Feature\RoutesTesting.php:1718
Have you tried delete cached files?
Delete everything in bootstrap\cache and try again on host.
I've explained the whole situation here, for another question, which in this case, it doesn't matter if it's testing or using in browser, when you cache your routes, laravel look for the cached file, instead of defined routes in web.php and api.php.
So if in cached file, you've had route with am/signin then, doesn't matter if you change it to signin or not, in web.php/api.php, it always looking for cached file, which in this case is am/signin.
Temporary questions, answer them by question number :
So you've commented everything in postSignin method, and didn't worked or just a part of it?
You said in browser is working, method is getting $lang from route? because in tests, as far as i can see, you're not passing anything.
Have you tried to change post to patch just for test? (that's because of Patch verb)
You might also try withoutExceptionHandling(); to get more details on error and test output. are you posting full test or just a basic test?
You can add this line to top of your test, $this->withoutExceptionHandling(); and get more details.
Remove $lang from method or just try a new method like below:
public function postSignin(Request $request){
return something or return $this->sendFailedLoginResponse($request); or etc.
}
How did you upgraded your project to Laravel 9? Create a new Laravel project and only test these two routes, get and post.

laravel - redirect to GET request after form is submitted

I have want to submit a form with post request where the method in the controller will redirect to a view.
Controller:
//Create quotation
public function quotation(Request $request){
$validated = $request->validate([
'parcel_weight' => 'required',
'parcel_size' => 'required',
'postcode_pickup' => 'required|postal_code:MY|exists:postcodes,postcode',
'postcode_delivery' => 'required|postal_code:MY|exists:postcodes,postcode'
]);
//logic to compute the quotation rate for each courier based on the inputs
//dd($request->all());
return redirect()->route('quotation.show');
}
//Show quotation
public function showQuotation(){
return view('orders.quotation');
}
web.php:
//Create new order
Route::get('/dashboard/orders','Dashboard\OrderController#index')->name('order.index');
//Generate quotation
Route::post('/dashboard/orders','Dashboard\OrderController#quotation')->name('order.quotation');
//Quotation page
Route::get('/dashboard/orders/quotation','Dashboard\OrderController#showQuotation')->name('quotation.show');
This code works fine but in order to hit the route('quotation.show'), data must be submitted from the form. If I just copy the URI and paste into the browser .../dashboard/orders/quotation then I will still be able to view the page without any input submitted. How do I prevent this?
Edit:
Using with() does not seem to work.
//Create quotation
public function quotation(Request $request){
$validated = $request->validate([
'parcel_weight' => 'required',
'parcel_size' => 'required',
'postcode_pickup' => 'required|postal_code:MY|exists:postcodes,postcode',
'postcode_delivery' => 'required|postal_code:MY|exists:postcodes,postcode'
]);
//logic to compute the quotation rate for each courier based on the inputs
//dd($request->all());
return redirect()->route('quotation.show')->with(['form','form']);
}
//Show quotation
public function showQuotation(){
if(request()->has('form')){
dd('Data has been submitted');
}else{
dd('NO DATA');
}
}
If you want to prevent direct navigation to a GET request (via entering a URL in your browser's URL bar, for example), then you'll need to add some back-end logic to prevent that. A quick solution is to include a session variable on the redirect(). This will include it in the session once, where you can then check it and act accordingly.
In the handler for your POST method:
return redirect()->route('quotation.show')->with(['submitted' => true]);
Then, in the handler for your GET method:
if (session()->has('submitted')) {
return view(...);
} else {
abort(403); // Unauthorized
// or
return redirect('/'); // Return home, etc
}
Sidenote: dd('Access') and dd('No Access') is good for debugging to see if your approach is working.
Edit: ->with() performs a "Flash", meaning submitted will be available for a single request only. If you need this to persist in the session longer (i.e. to facilitate refreshing the page), adjust the code:
session()->put('submitted', true);
return redirect()->route('quotation.show');
You'll now be able to refresh the page after being redirected, but you will also be able to navigate away, then manually back and still see your results. It's a give and take solution.

Control where a redirect goes after failed validation

Is it possible to set the redirect path should a request fail validation in Laravel 7? Example:
public function handleForm(Request $request)
{
if (! $request->validate(['someData' => 'required|size:12|alpha_num'])) {
return redirect(...);
}
}
In this particular case, if someData doesn't validate, Laravel redirects me to the path the request originally came from. This is not the behavior I want to see. I would like to be able to define a different path to redirect to. Is that possible?
Use Laravel Validation's fails() method to check if it fails, then redirect on which route you desired.
$validator = Validator::make($request->all(), [
'someData' => 'required|size:12|alpha_num',
]);
if ($validator->fails()) {
return redirect(...);
}
documentation

automatically redirects to index page instead of desired page

I have a taskController controller in my laravel application.Inside my resource folder i have have three pages under resource/views/taksController/
1.index.blade
2.store.blade
3.create.blade..
in my create.blade i have a form which on submit will go through a validation and if succeeded i want it to be redirected to store.blade ,otherwise it will redirect to create.blade again to fill up the form again.But here in my program ,on success it doesn't redirect me to store.blade file, rather it redirect me to index.blade.Why is this happening?How i can solve this?
i am using laravel 5.2
In my route.php i added the controller like
Route::resource('taskController','taskController');
in taskController the validation logic inside controller is like the following:
public function index()
{
//
return View::make('taskController.index');
}
public function create()
{
//
return View::make('taskController.create');
}
public function store(Request $request)
{
$rules = array(
'email' => 'required|email', // required and must be unique in the ducks table
'comment' => 'required',
'agree' => 'required|accepted' // required and has to match the password field
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
echo 'bal';
// redirect our user back to the form with the errors from the validator
return Redirect::route('taskController.create');
}else{
return Redirect::route('taskController.store');
}
}
The URL used for the index route and the store route are the same. The difference is the HTTP verb that is used on that URL. GET requests to the URL will take you to the index, whereas POST requests to the URL will take you to the store.
In your store() method, when you return Redirect::route('taskController.store');, the route() method converts the parameter to the URL, and then makes a GET request to it. This is why you are redirected to index.
Generally, your store, update, and destroy routes don't have views associated with them. They are meant to perform an action and then redirect to the route that contains the view.
For example, the general workflow for creating a new resource is:
create route shows create view which has the form,
form POSTs to store route,
store route attempts to create new resource,
if validation fails, store route redirects back to create route with errors,
if resource is created successfully, store route redirects to the show route, with the id of the newly created resource.
The workflow for editing a resource is similar:
edit route shows edit view which has the form,
form PUTs to update route,
update route attempts to edit the resource,
if validation fails, update route redirects back to edit route with errors,
if resource is modified successfully, update route redirects to the show route, with the id of the modified resource.
i think you should have this:
public function index(){
return view('taksController.index');
}
public function create(){
return view('taksController.create');
}
public function store(Request $request)
{
//
$rules = array(
'email' => 'required|email', // required and must be unique in the ducks table
'comment' => 'required',
'agree' => 'required|accepted' // required and has to match the password field
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
// get the error messages from the validator
$messages = $validator->messages();
//echo 'bal';
// redirect our user back to the form with the errors from the validator
return Redirect::route('taskController.create');
}else{
return view('taksController.store');// redirects me to index.blade instead of store.blade
}
}

Laravel Facebook login - no callback (localhost)

My first question: is it possible to test this on a localhost? (Because I can imagine that this could be my problem)
I read the docs and did everything like it is described. I browser to /auth/facebook and I get redirected to Facebook where I "accept" the terms. I get redirected to this link: http://localhost:8000/auth/login#_=_
So I tried to debug and did a dd($user); in my Authcontroller, but there was no output given.
public function redirectToProvider()
{
return Socialite::driver('facebook')->redirect();
}
public function handleProviderCallback()
{
$user = Socialite::driver('facebook')->user();
dd($user);
// $user->token;
}
Anyone an idea what I did wrong?
Need to see your routes configuration for more info, but will give it a shot with the info you provided.
Note that you are getting redirected to http://localhost:8000/auth/login#_=_.
That looks like you are getting redirected to your app's login page after authorizing on facebook.
In config/services.php, make sure that, for your facebook login configuration, your redirect url points to a route which you have defined in your routing configuration to handle the callback.
e.g.
// config/services.php
...
'facebook' => [
'client_id' => 'my_facebook_client_id',
'client_secret' => 'my_facebook_client_secret',
'redirect' => 'http://localhost:8000/auth/facebook/callback',
],
...
The route http://localhost:8000/auth/facebook/callback should then be defined in the routing configuration:
// app/Http/routes.php
...
Route::get('auth/facebook/callback', 'Auth\AuthController#handleProviderCallback');
...
Note that the routing config has to allow GET requests since the user will be redirected.
Your dd($user) should work just fine with this setup.
How you save the user data depends on your model architecture.
For instance, in a simple case where you have no other registration method and only use facebook login, you could do this:
public function handleProviderCallback()
{
$facebookData = Socialite::driver('facebook')->user();
// check if already in DB
try{
$user = User::where('facebook_id', $data->id)->firstOrFail();
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
// create a new user
$user = new User();
// set the properties you want
// $user->facebook_id = $data->id;
// ...
// then save
$user->save();
}
// login the user
Auth::login($user);
// perhaps return a redirect response
return redirect()->action('MyController#myAction');
}

Categories