Context
Laravel ships with two authentication controllers out of the box, which are located in the App\Http\Controllers\Auth namespace.
...
You may access the authenticated user via the Auth facade: $user = Auth::user();
Reference: Laravel 5.2 Documentation
I'm able to log in successfully and I'm redirected to the correct place as defined in the AuthController.php, but now I need access to the $user object in most of my views such as for checking the user's information, access priveleges, etc.
Problem
How do I properly provide access to the $user variable on all of my views?
How other people have been doing it
User imJohnBen of Laracast asked how a Laravel 5 service provider can be used to share view variables. He later shares how he was able to use the existing ComposerServiceProvider and added a GlobalComposer to be able to share variables on all the views.
I followed his answer but there was a missing step. I couldn't contribute to the Laracast forums, thus leading to the creation of this StackOverflow question.
The Laravel version I'm using here is Laravel 5.2.*.
Answer
Find the existing ComposerServiceProvider class. I found mine in vendor/laravel/framework/src/Illuminate/Foundation/Providers/ComposerServiceProvider.php.
Import/reference the ViewFactory dependency at the top of the file.
use Illuminate\Contracts\View\Factory as ViewFactory;
Add the boot method, or modify it if it exists already. Make sure the ViewFactory was injected (add it as a parameter in the boot function):
/**
* Register bindings in the container.
*
* #return void
*/
public function boot(ViewFactory $view)
{
$view->composer('*', 'App\Http\ViewComposers\GlobalComposer');
}
Make a ViewComposers folder in your app/Http folder.
Make a GlobalComposer.php file in the ViewComposers folder, containing the following:
<?php
namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Auth;
class GlobalComposer {
/**
* Bind data to the view.
*
* #param View $view
* #return void
*/
public function compose(View $view)
{
$view->with('user', Auth::user());
}
}
(The missing step) Finally, make sure everything is wired up by going to your config/app.php file and making sure that ComposerServiceProvider is in your providers list.
'providers' = [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
// etc...
Illuminate\Foundation\Providers\ComposerServiceProvider::class,
]
Afterwards, the $user variable and any other variables you define in the GlobalComposer will be accessible in any of the views you render.
Related
I am figuring out how Prestashop 1.7 works and I have some experience with Symfony.
In Symfony development mode [Symfony project url]/_profiler is useful, among other things, to check the dump($someVariable) of variables in a request.
With Prestashop 1.7 in the admin mode it is possible to do [Prestashop project url]/admin[some random chain of chars]/_profiler to display the Symfony _profiler and analyse what's going on in the requests concerning the admin mode.
But if outside the admin mode (in the virtual shop demo mode), [Prestashop project url]/_profiler or [Prestashop project url]/[language value]/_profiler does not display the Symfony _profiler.
I have tried Prestashop own profiler by activating define('_PS_DEBUG_PROFILING_', true); in [prestashop project]/config/defines.inc.php. It displays Prestashop profiler at the bottom of the "virtual shop demo mode" but this one does not include dump($someVariable) that could be used, for development and to understand Prestashop behaviour, in a hookAction[action name].
I've managed to get the Symfony dump($someVariable) with hookDisplay[display name] through the HTML generated but not in a hookAction[action name] which is what I am looking for.
UPDATE
Looking at Prestashop 1.7 code I almost have the feeling that Symfony is only used on the Admin side, because I can see:
$kernel = new AppKernel(_PS_MODE_DEV_?'dev':'prod', _PS_MODE_DEV_); in [Prestashop project url]/admin[some random chain of chars]/index.php but I don't see it in [Prestashop project url]/index.php.
Best solution I've found so far is to create a custom logger similar to the one explained here
I've created file: [Prestashop project]/modules/[my module]/classes/CustomLogger.php
<?php
class CustomLogger {
const DEFAULT_LOG_FILE ="prestashop_system.log";
public static function log($message, $level = 'debug', $fileName = null){
$fileDir = _PS_ROOT_DIR_ . '/log/';
$fileName=self::DEFAULT_LOG_FILE;
if(is_array($message) || is_object($message)){$message = print_r($message, true);}
$formatted_message=$level." -- ".date('Y/m/d - H:i:s').": ".$message."\r\n";
return file_put_contents($fileDir . $fileName, $formatted_message, FILE_APPEND);
}
}
?>
In '[Prestashop project]/modules/[my module]/[my module].php' it is declared at the top:
include_once dirname(__FILE__).'/classes/CustomLogger.php';
And use CustomLogger::log($[some variable]); in your code.
I am using Laravel 5.4 and the package migrations-generator that generates migrations.
So I have the migrations and now I need to generate the views automatically using Artisan. I tried it on Symfony and it was so easy but I can't do it with Laravel.
Here is an example of a migration file called 2017_07_01_202030_create_personas_table.php for persons.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreatePersonasTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('personas', function(Blueprint $table)
{
$table->integer('id', true);
$table->string('nombre', 100);
$table->dateTime('fecha_de_nacimiento');
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('personas');
}
}
I tried more than eight packages to resolve my problem: generate model, views and controller from a table (on Laravel 5.4) but they don't work. Else I will use the Yii Framework that works great.
php artisan make:controller MyController -r --model=MyModel
It will generate Controller with REST function inside them. & also create model if its not created.
You can also use below command to generate migration while creating Model
php artisan make:Model MyModel --migration
& For manage views you can use this. I haven't used it yet but come to see this package suggest by many time.
https://github.com/svenluijten/artisan-view
Hope this help.
If you want an easy way to generate migration and views in a single artisan command, just install & use this popular package from Jeffrey Way https://github.com/laracasts/Laravel-5-Generators-Extended. Just follow the steps from that page.
I've been trying to get the create account form (register form) in a pop-up on the front page, without any success.
Can anybody here help me out with an example that works?
I've tried adapting examples from Drupal 7 but couldn't get them to work, I've tried to make a custom form but it didn't work, I've tried installing modules that could handle this but they also didn't work.
The last attempt I've made to resolve this problem was:
<?php
/**
* #file
* Functions to support theming in the themename theme.
*/
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;
/**
* Implements hook_preprocess_HOOK() for HTML document templates.
*/
function themename_preprocess_html(&$variables) {
$form = \Drupal::formBuilder()->getForm('Drupal\user\register');
return $form;
}
Any help would be greatly appreciated.
Thank you!
you can use this module: https://www.drupal.org/project/formblock which exposes some additional forms as blocks (like the user registration, new password, contact, etc..). So after you install it you can just configure the block to appear only on the front page. The registration block will not be available for authenticated users or if the anonymous users are not allowed to create new accounts.
However, you will also have to apply this patch https://www.drupal.org/node/2570221 (if it will not be already committed by the time you check it) if you use the latest Drupal8 stable version, otherwise you will get a fatal error.
This link explains how it can be used to programmatically render the login and registration forms.
http://web-tricks.org/content/how-render-user-login-form-and-user-register-form-drupal-8
For the login form
$form = Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class) ;
$render = Drupal::service('renderer');
$variables['login_form'] = $render->renderPlain($form);
and for register form
$entity = \Drupal::entityTypeManager()->getStorage('user')->create(array());
$formObject = \Drupal::entityTypeManager()
->getFormObject('user', 'register')->setEntity($entity);
$form = \Drupal::formBuilder()->getForm($formObject);
$variables['register_form'] = \Drupal::service('renderer')->render($form);
I am building restful stateless API using Yii2... So far so good. Now I failed at rookie problem.
I have decided to make API application (preferred by Yii) and make API as a module. So my structure is:
- modules
-- v1
--- components
--- controllers
--- models
Inside v1 folder of course there is Module.php. In here I do authentication like:
$behaviors['authenticator'] = [
'class' => HttpBasicAuth::className(),
'auth' => function($username, $password) {
... get user's data from DB ...
[HERE]
}
];
and at point [HERE] I sotre user's ID in public variable.
So far so good...
So when I for example call v1/abc/index abc controller loads in inside that controller I would like to access user's ID stored at point [HERE]. Any idea?
To access module from controller, you should simply use $this->module.
And from a view : $this->context->module.
No need to use getModule() here.
Read more : http://www.yiiframework.com/doc-2.0/yii-base-controller.html#$module-detail
PS: to access module outside its controllers/views you could use :
Yii::app()->getModule('module');
Have you tried
$v1Module = Yii::app()->getModule('v1');
And then simply
echo $v1Module->yourPublicVariable;
I am trying to initiate the AdminController module from outside the Prestashop. Basically, I am creating an external program which uses Prestashop to get current employee for which I should instantiate the AdminController, but its throwing error.
Many modules init the FrontController but I cannot find any example for AdminController like :
include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../init.php');
Please advice.
I found the solution after all. Simply define _PS_ADMIN_DIR_ and init the config.inc.php, Prestashop will automatically load the admin environment. However, if you are loading this from a module, its tricky to find the admin directory as its not defined anywhere, so I have written this small script.
$admindir = '';
foreach (glob("../../*/ajaxfilemanager", GLOB_ONLYDIR) as $filename) {
$admindir = str_replace('../../', '', $filename);
$admindir = str_replace('/ajaxfilemanager', '', $admindir);
}
define('_PS_ADMIN_DIR_', getcwd().'/../../'.$admindir);
require(_PS_ADMIN_DIR_.'/../config/config.inc.php');
Enjoy!