I want to track the device name of the user have used for accessing the site. for that I'm using antonioribeiro/tracker But while accessing the device name it's showing
Trying to get property of non-object
Here is the controller I have used for that:
public function postUser(Request $request)
{
$user=new User();
$user->name= $request->Input(['name']);
$user->email=$request->Input(['email']);
$user = Tracker::currentSession();
dd($user->device->platform) ;
//dd( $user->device->is_mobile);
// $pageViews = Tracker::pageViews(60 * 24 * 30);
// dd($pageViews);
$user->save();
return redirect('userPage');
}
How do I resolve my problem. If anyone find the solution please provide a valid one.
Related
I am using Sentinel in Laravel 5.4. What I am trying to do is: get logged user detail but Sentinel::getUser() returns null. For this process, I have seen this instruction in this answer
. I am following using View Composer method.
Steps I have done
I have created a file ViewComposerServiceProvider inside Providers folder. It looks like:
public function boot()
{
$user = Sentinel::getUser(); //<<-- main error: dd($user) returns empty
$userDetail = UsersDetail::where('user_id', $user->id)->firstOrFail();
if ( is_null ($userDetail) ) {
$userDetail = new UsersDetail;
}
view()->composer('backend.*', function($view) {
$view->with('userDetail', $userDetail);
//$view->with('userDetail', 'Test'); //this works fine
});
}
Then, I register this provider in config/app.php Providers array as
App\Providers\ViewComposerServiceProvider::class,
When, I pass other variables in userDetail, it's working perfectly. But, I cannot get the logged in user detail. Am I missing something?
Following the first solution from this answer also seems not working since, construct are run prior to the Middleware. Any help please.
Go to app\Providers\AppServiceProvider.php
Then your serviceProvider.php boot method like below
public function boot()
{
$user = Sentinel::getUser(); //<<-- main error: dd($user) returns empty
$userDetail = UsersDetail::where('user_id', $user->id)->firstOrFail();
if ( is_null ($userDetail) ) {
$userDetail = new UsersDetail;
}
View::composer('userDetail', function($view) use($userDetail ) {
$view->with('userDetail ',$userDetail );
});
}
Then your userDetail.blade.php you can access userDetail data like this
{{ $userDetail }}
I want to give a 3rd party PHP application access to Yii2 user data (HumHub) and have tried this:
function getUserId() {
require_once('../protected/vendor/yiisoft/yii2/Yii.php');
$yiiConfig = require('../protected/config/common.php');
(new humhub\components\Application($yiiConfig));
$user = Yii::$app->user->identity;
return $user;
}
This does not work. There are no errors up until new humhub\components\Application($yiiConfig) but then the 3rd party app breaks with no error thrown and the function does not return anything.
I did find this solution which does not work.
Is there are reason this does not work or is there an alternate solution to getting Yii2 user data properly?
This is how to do it in HumHub V1.0
require_once('../protected/vendor/yiisoft/yii2/Yii.php');
$config = yii\helpers\ArrayHelper::merge(
require('../protected/humhub/config/common.php'),
require('../protected/humhub/config/web.php'),
(is_readable('../protected/config/dynamic.php')) ? require('../protected/config/dynamic.php') : [],
require('../protected/config/common.php'),
require('../protected/config/web.php')
);
new yii\web\Application($config); // No 'run()' invocation!
Now I can get $user object:
$user = Yii::$app->user->identity;
Indeed an error should be thrown, but, the error settings of your PHP may be overridden or set to not display errors.
You call undefined object Yii::$app->user->identity. The reason, from documentation because you have not initialized the Yii object. So your code should be as follows:
function getUserId() {
require_once('../protected/vendor/yiisoft/yii2/Yii.php');
$yiiConfig = require('../protected/config/common.php');
(new humhub\components\Application($yiiConfig)); // try to comment this line too if it does not work
// Add The Following Line
new yii\web\Application($yiiConfig); // Do NOT call run() here
$user = Yii::$app->user->identity;
return $user;
}
I'm working in Laravel 5.1 and saving a gecko to a database. My code for my store method is below:
public function store(GeckoRequest $request)
{
$user_id = Auth::user()->id;
$input = $request->all();
$input['genetics'] = json_encode($input['genetics'], JSON_FORCE_OBJECT);
$input['user_id'] = $user_id;
Gecko::create($input);
$name = str_replace(' ', '-', $request['name']);
flash()->success('Success!', 'Your gecko has been added to the system');
return redirect()->action('GeckoController#show', [$name]);
}
I know I could do $input['uid'] = str_random(10); - But how do I ensure it is in fact unique and won't redirect back to my form if it isn't unique?
Is there a proper practice into achieving something like this?
Create a function that generates the 10 digit random key then passes it through a validator with a unique rule set. If the validator gives you an error re-run the same function to generate a new one
public function randomId(){
$id = \Str::random(10);
$validator = \Validator::make(['id'=>$id],['id'=>'unique:table,col']);
if($validator->fails()){
return $this->randomId();
}
return $id;
}
From what I understand of your question, you could achieve this using a created event on the model. This will allow you to add anything to the model before it is persisted in the database without any further interaction required.
In a service provider, or your App\Providers\AppServiceProvider add the event to the boot method.
public function boot()
{
User::creating(function ($user) {
// When ever a User model is created
// this event callback will be fired.
$user->setAttribute('randomString', str_random(10));
// Returning 'false' here will stop the
// creation of the model.
});
}
Full documentation for eloquent model events.
Here is something I've used before:
do
{
$code = // generate your code
$gecko_code = Gecko::where('code', $code)->first();
}
while(!empty($gecko_code));
I'm setting up a Laravel 5.1 project and I've been making good progress with it but have run in to something that I'm struggling to figure out.
Basically, I have been creating objects to insert in to the database in my controller methods. This hasn't been too bad because they're usually one-liners.
However, I've run in to a more complex db entry and my controller has become a little muddied. Let me show you:
/**
* Store a new ticket for the specified project.
*
* #param int $id
* #param TicketsRequest $request
* #return Response
*/
public function store_ticket($id, TicketsRequest $request)
{
$user_id = Auth::user()->id;
$project_id = $id;
$project_tickets = Ticket::whereProjectId($id);
$project_ticket_id = $project_tickets->count() + 1;
$ticket = new Ticket;
$ticket->user_id = $user_id;
$ticket->project_id = $project_id;
$ticket->project_ticket_id = $project_ticket_id;
$ticket->title = $request->title;
$ticket->save();
$ticket_update = new TicketUpdate;
$ticket_update->user_id = $user_id;
$ticket_update->ticket_id = $ticket->id;
$ticket_update->status_id = $request->status_id;
$ticket_update->priority_id = $request->priority_id;
$ticket_update->assigned_to = $request->assigned_to;
$ticket_update->description = $request->description;
$ticket_update->save();
return redirect('/projects');
}
So as you can see, I'm creating a ticket which gets saved to the database, then also creating a ticket update which is also saved to the database.
What I'd like to do is extract this code in to 'something' to clean up my controller.
On my travels, I've found that maybe creating repositories might be the way forward. Otherwise I was thinking about some kind of service but I'm not really convinced that that is the way forward.
I have a subscription to Laracasts and found the following video but it's a little outdated and I was sure if this would still be the 'right' way to do this in Laravel 5.1 (I've found that things seem to have a natural home in 5.1 compared to older versions).
https://laracasts.com/lessons/repositories-simplified
Any suggestions/links etc would be great. Thanks!
If you instantiate your objects often/always using the same set of attributes, you could easily extract that code into models constructors, e.g:
//in your model
public function __construct($user_id, $ticket_id, $request) {
$this->user_id = $user_id;
$this->ticket_id = $ticket_id;
$this->status_id = $request->status_id;
$this->priority_id = $request->priority_id;
$this->assigned_to = $request->assigned_to;
$this->description = $request->description;
}
// in your controller
$ticket_update = new TicketUpdate($user_id, $ticket->id, $request);
$ticket_update->save();
Nothing wrong with your implementation. I suggest you use try catch when calling the save() method in case something goes wrong and send a nice error to the user saying something like "something went wrong, contact your admin".
I'm trying to get user object inside an entity. I'm using FosUserBundle and PugxMultiUserBundle, and I tried the following command:
container->get('fos_user.user_manager')->getToken()->getUser();
but I get:
Undefined property $container
How can I fix it?
Thank you for your help.
The function that doesn't work is inside an entity, and it is the following:
protected function getUploadDir()
{
$userManager = $this->container->get('security.context');
$user = $userManager->findUserByUsername($this->container->get('security.context')
->getToken()
->getUser());
return 'uploads/'.$user;
}
UPDATE after #OP edited...
You cannot access the container (hence the userManager) from an entity. The entity should not access the container itself.
You are missing $ before the name of your variable.
But that's not all, solution inside a controller :
$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->findUserByUsername($this->container->get('security.context')
->getToken()
->getUser())
But, inside a controller, your should be able to get user by doing the following :
$this->getUser();