Laravel 5 - Middleware get user ID and send to controllers - laravel

Hello guys !
I'm working on an API that has a middleware authenticating the user with a unique ID. After making sure that this user exists, I want to send his database ID to the controller coming next, whichever it is.
Is that a good idea ? Or should I get that ID somehow after the middleware finished ?
How do I do that ?
Thanks !

Is that a good idea ? Or should I get that ID somehow after the middleware finished ?
It depends on what you want to do and how you routes are declared.
The routing is one of the first thing initialized by Laravel. You cannot pass parameter at run time (correct me if I'm wrong).
Plus, the controllers called after all midlewares has done their work.
I cannot garanty it's the more "beautiful" way to do this, but what i'm use to do is using Session::flash() or Session::put() when I want to pass parameters to my controllers at run time.
I use Session::flash() if the parameter has a one request life time, and Session::put() when I want the variable be more 'consistent' across the whole application.
I don't know if I am clear or not, tell me :)

Well, as long as you don't send that ID passing through the HTTP protocol, you should be fine since the user won't be able to tamper with the data.
That said, if you are using Laravel's built-in Auth module, you should just do an Auth::user() call at the other controller and it will give you the authenticated user.
If that isn't an option, you should create a function in the other controller that accepts $id as a parameter. You can call that function from within the first controlling by constructing the second controller throug $secondController = App->make(SecondController) and then $secondController->receiverFunction($id)

If you want the currently-authenticated user available in your application, just add it your base controller:
<?php namespace App\Http\Controllers;
use Illuminate\Contracts\Auth\Guard;
abstract class Controller {
protected $auth;
protected $currentUser;
public function __construct(Guard $auth)
{
$this->auth = $auth;
$this->currentUser = $this->auth->user();
}
}

Related

Laravel 5: find the page number of an entry

I'm working on a custom forum and when a post is added to a thread I have to notify the subscribed users. In the message I have to place the link for the user to go straight to the post. Something like this:
/forum/discussion/1/ateliers-et-expositions?page=2#forum-message-3
To be able to do that I need to know the page number of the entry. Does this feature exist on Laravel already? I couldn't find it in their docs and I know about features that exist but are not in their docs, so maybe it's there already and I'm just not aware of it.
I would like to avoid making a select in the database a loop through it to find the page number, if possible.
You most likely look for get() method of Request class. Assuming you want to get this in your controller method, say foo(), you should have:
use Illuminate\Http\Request;
public function foo(Request $request)
{
$page = $request->get('page');
...

\Request::getSession() returns NULL in Controller construct

I want to get the session id of the user each time a page is loaded so I use \Request::getSession()->getId() in the controller construct but I get this error
Call to a member function getId() on null
If I use same code in any of the route methods, it works.
How can I solve this?
Try use Illuminate\Support\Facades\Auth; Auth::getSession()->getId();
This is the default functionality of Laravel. Session data is no longer available in the constructor. See:
laravel - Can't get session in controller constructor
Taylor's word about it :
It’s very bad to use session or auth in your constructor as no request has happened yet and session and auth are INHERENTLY tied to an HTTP request. You should receive this request in an actual controller method which you can call multiple times with multiple different requests. By forcing your controller to resolve session or auth information in the constructor you are now forcing your entire controller to ignore the actual incoming request which can cause significant problems when testing, etc.
This worked for me:
public function __construct()
{
// No session access from constructor work around
$this->middleware(function ($request, $next) {
\Request::getSession()->getId();
return $next($request);
});
}

Difference Between index.php?id=1 and index.php/id/1

If I want to create RESTful APIs, which one should I choose?
How do the URLs as index.php/id/1 work? I think it's a file path, not a URL.
If I want to get an image as abc.com/img/1.png, it may have conflicts with abc.com/img/{param}. How do I solve?
BTW, I use Laravel now.
Thanks so much.
The difference is in route model binding
https://laravel.com/docs/5.7/routing#route-model-binding
This allows you to get the model with the id that is passed into the route
So for example a route like this:
Route::get('users/{user}', 'UsersController#getUser');
Will allow you to do this in you method:
use App\User
public function getUser(User $user) {
return $user;
}
This means that you get the full record for the id that is in the route.
So your Questions:
1: I would use this for sending model id's
2: the variables in the route are passed in that order to the method allowing you to get access to them.
3: You will need to be careful with your routes as you can have conflicts. having said that Laravel does not use a traditional directory structure for storage. I believe that if you have a folder stucture of /public/img and that folder contains an img named 1.png it will get the image but I have not tested this.

Laravel register extra fields placement

I have some extra fields that need to be filled right after a user is registered.
Right now I've done it with an Event and couple of Listeners but I can't seem to find an elegant way to carry the data from the Registration page to the Listener so it can insert it in.
Should I use Events/Listeners or is there a better way (without changing the registerController).
I was thinking of getting rid of the Events and redirecting to another form right after registering where the other data to be inserted, but it's just couple of fields, so if there's a better way I would appreciate you sharing it.
Latest Laravel version with the default Auth installed.
I know you said without changing the RegisterController, but this way it doesn't change any of the logic inside it:
class RegisterController extends Controller
{
use RegistersUsers;
protected function registered(Request $request, $user)
{
// ... your code here
return redirect($this->redirectPath());
}
}
If your class has a registered() method it will be called right after a successful registration, so you can save the additional data there and then redirect the user.

Codeigniter Filters

I am working on the admin side of a site that I am building and wanted to lock it down. I already figured out how to do my authentication, but I am looking for a way to call this authentication function on every request being made in this controller without having to call it at the beginning of each controller method. Is there a way to pass request through a filter, or something of the sort, in the constructor?
Ex.
public function __construct()
{
filter(authenticate(), 'login,signin');
}
Where the first parameter is the method being called, and the second parameter is the methods to exclude from the filter. Because you wouldn’t want to check for a logged in user if they are on the login page or if the signin method is being used since it is the one logging them in. Does anyone know if there is a way to do this? I think it would cut back on me repeating the call to authenticate before each locked down method.
Thanks!
Figured it out
Remapping looks to have done what I was looking for. Be sure to look into it! Great function :)
Have you considered using a MY_Controller?
In MY_Controller.php, create an Auth_Controller class (name it what you like) which will check if the user is logged in in the __construct() method. Then, ave all your "locked down" controllers extend Auth_Controller.

Resources