I have functions setAttribute($key, $value) and getAttribute($key, $default) in my User class. When the user is authenticated I want to set several attributes to be set that will be used later in various controllers.
I tried setting the attributes in my success handler function:
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$token->getUser()->setAttribute("user_data_set", 1);
}
But when I tried calling it in my controller the value has not been set
public function indexAction(Request $request) {
//Get the logged in user
$user = $this->getUser();
//Entity Manager
$em = $this->getDoctrine()->getManager();
// this page is just used as the starting point to redirect the user to the appropriate page
if($user->getAttribute("user_data_set", 0) == 1)
{
//Get Symfony1 route from the user data table
$old_homepage = $user->getAttribute("user_homepage", "#default_homepage");
//Convert route to Symfony2 format
$new_homepage = $this->setForwardingAddress($old_homepage);
return $this->redirect($this->generateUrl($new_homepage));
}
else
{
return $this->redirect('login');
}
}
How can I modify the global user instead of a local reference?
You obviously want cross-request solution so you'll need to use DB or session.
For example:
// Injecting Session service
public function __construct(Session $session){
$this->session = $session
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
$this->session->set('user_data_set', 1);
}
And then in your controller:
$foo = $session->get('user_data_set');
Is this what you wanted?
Related
I have store() in controller, and in this place I call 3 functions. Variable $users store correct fields validation with values them. In next step I call function which hash password. At the end I call function which add user to database. My problem is that hash password is not add to database.What can I do that pass hashPassword to createUser() ?
public function store(RegistrationRequest $request, UserService $user)
{
$user = $request->correctValidate();
$userService->hashPassword($user['password']);
$userService->createUser($user);
}
public function createUser($request): void
{
User::create($request);
}
public function hashPassword($request)
{
return Hash::make($request);
}
public function correctValidate()
{
return $this->validated();
}
#Deks2 Please try below solution:
$user['password'] = $userService->hashPassword($user['password']);
I am generating a pdf based on user input. I can call the databse and get ALL contract info using all(). However, I would only like to generate a pdf for one of the values. Each contract has a auto incrememnt id which i could use.
Whats the best way to communicate between controllers so only the contract I am referencing is used to generate a pdf?
PdfGenerateController:
public function pdfview(Request $request)
{
$users = DB::table("users")->get();
$contract = Contract::all();
view()->share('users',$users);
if($request->has('download')){
// Set extra option
PDF::setOptions(['dpi' => 150, 'defaultFont' => 'sans-serif']);
$users = DB::table("users")->get();
// pass view file
$pdf = App::make('dompdf.wrapper');
$pdf->loadHTML
($contract);
return $pdf->stream();
}
return view('sell.contract');
}
Contract Controller (user input)
public function store(Request $request)
{
$contract = new Contract;
$contract->buyer_first_name = $request->input('buyer_first_name');
$contract->listing_id = $request->input('listing_id');
$contract->save();
return redirect()->route('generate-pdf')->with('contracts',$contract);
}
Storing the contract id in the session is probably your best bet. If you need to use it only on the next request, you could just flash it (in fact, that's exactly what the redirect(..)->withInput(sessionKey, val) does).
Something like that:
Contract Controller
public function store(Request $request)
{
// ...
$contract->save();
session(['contract_id' => $contract->id]);
return redirect()->route('generate-pdf');
}
Or just flashing:
public function store(Request $request)
{
// ...
$contract->save();
return redirect()->route('generate-pdf')->with('contract_id', $contract->id);
}
PdfGeneratteController
public function pdfview(Request $request)
{
$contract = Contract::findOrFail(session('contract_id'));
// ...
}
I would probably create a PDF model class with a static method to generate the PDF.
class PDF
{
public static function generatePDF($id, $isDownload)
{
// ...
}
}
Then you could simply call the static method from the Contact controller and pass the required data as parameters.
public function store(Request $request)
{
// ...
\PDF::generatePDF($contract->id, $request->has('download'));
// ...
}
I am seeing some behaviour. I can't explain when accessing user data via the Auth facade in Laravel class. Here's an extract of my code:
private $data;
private $userID;//Set property
function __construct()
{
$this->middleware('auth');//Call middleware
$this->userID = Auth::id();//Define property as user ID
}
public function index() {
return view('');
}
public function MyTestMethod() {
echo $this->userID;//This returns null
echo Auth::id();//This works & returns the current user ID
}
I am logged in and have included use Illuminate\Support\Facades\Auth; in the class thus the code works, but only when accessing Auth in methods - else it returns a null value.
Most odd, I can't work out what is causing this. Any thoughts much appreciated as ever. Thanks in advance!
In Laravel Laravel 5.3.4 or above, you can't access the session or authenticated user in your controller's constructor, since the middlware isn't runnig yet.
As an alternative, you may define a Closure based middleware directly in your controller's constructor.:
try this :
function __construct()
{
$this->middleware(function ($request, $next) {
if (!auth()->check()) {
return redirect('/login');
}
$this->userID = auth()->id(); // or auth()->user()->id
return $next($request);
});
}
another alternative solution go you your base controller class and add __get function like this :
class Controller
{
public function __get(string $name)
{
if($name === 'user'){
return Auth::user();
}
return null;
}
}
and now if your current controller you can use it like this $this->user:
class YourController extends Controller
{
public function MyTestMethod() {
echo $this->user;
}
}
You should try this :
function __construct() {
$this->userID = Auth::user()?Auth::user()->id:null;
}
OR
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->userID = Auth::user()->id;
return $next($request);
});
}
When I am trying to send mail, everytime a new member is added to the user table, so that they can get a setup password link. I have been trying to get this to work but seem not to be.
public function store(AddUser $request)
{
$user = $request->all();
$user['activate'] = $this->active();
$user['guid'] = $this->guid();
$user['accountno'] = $this->generateAndValidateAccountno();
$check = User::find($user['phone']);
if(!$check) {
$id = User::create($user);
$this->sendEmail($user['accountno']);
}
return redirect('employee');
}
public function sendEmail(Request $request, $id)
{
$user = User::find($id);
Beautymail::send('emails.welcome', [], function($message)
{
$message
->to('$id->email', '$id->fname')
->subject('Welcome!');
});
}
}
Not sure what am doing wrong
Just use the same request class in the controller and the model. In your user model, add use Illuminate\Http\Request at the top of the class to tell it which Request class to use.
Just change:
public function sendEmail(Request $request, $id){...}
to
public function sendEmail($id){...}
I've started a Silex project a week ago and still getting some issues within the service-container. Although being quite simple.
Here is what happens to me:
$app->post('/', function (Request $request) use ($app) {
$success = (new \Malendar\Application\Service\User\LoginUserService($app['user_repository'], $app['session']))->execute($request);
if ($success) {
return $app->redirect($app["url_generator"]->generate("calendar"));
} else {
return new Response($app['twig']->render('login.html', ['formError' => true]), 400);
}});
I've created a LoginUserService class that given my user respository and the session service I'm able to login the user, that means, compare to database and checking that both username and password are in the system. That works perfectly but the issue comes with the session provider. Here is the class code:
class LoginUserService implements ApplicationServiceInterface
{
private $userRepository;
private $session;
public function __construct(UserCaseRepository $userRepository, Session $session)
{
$this->userRepository = $userRepository;
$this->session = $session;
}
public function execute($request = null)
{
// TODO: Implement execute() method.
$userName = $request->get('user');
$password = $request->get('password');
$user = $this->userRepository->findByUsername($userName);
var_dump($user);
if (!empty($user) && $user->validate($password)) {
$this->session->start();
$this->session->set('id', $user->getUserId());
$this->session->set('username', $user->getName());
$this->session->set('email', $user->getEmail());
$this->session->save();
return true;
} else {
return false;
}
}
}
$this->session which I believe gets the app['session'] do not set the value of username, email and id, they remain null, and I can assure you that all data is well provided.
On the other hand, If I'm doing it outside the class, it works and the username it is set:
$app->post('/', function (Request $request) use ($app) {
$success = (new \Malendar\Application\Service\User\LoginUserService($app['user_repository'], $app['session']))->execute($request);
$app['session']->set('username', 'Pedro');
But of course it would like to pursue the usage of my loginService what do I am missing?
Thank you beforehand =)