I am using owen-it/laravel-auditing for keeping history of changes of prices of products. But I am getting error while updating prices.
OwenIt \ Auditing \ Exceptions \ AuditingException Invalid
UserResolver implementation
Prices do get updated but is history is not updated in database
Products.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Auth;
use OwenIt\Auditing\Contracts\Auditable;
use OwenIt\Auditing\Contracts\UserResolver;
class Products extends Model implements Auditable, UserResolver
{
use \OwenIt\Auditing\Auditable;
protected $table = 'products';
protected $fillable = ['name','price','season','category','description','stock','image'];
protected $auditInclude = [
'name',
'price',
];
public static function resolveId()
{
return Auth::check() ? Auth::user()->getAuthIdentifier() : null;
}
}
From what I can see, #Faiez is using version 4.x or 5.x of the Auditing package, which registers the User resolver differently, when compared to the new 6.x version, which is what #btl was answering for.
You'll have to update your audit.php configuration file with the following, to make it work:
return [
// ...
'user' = [
// ...
'resolver' => App\Products::class,
// ...
],
// ...
];
However, I would advise you to move the User resolver to a different class (the User model, perhaps?), since it doesn't make much sense to have that in the Products model.
When in doubt, check the documentation
You need to set the resolver class in the config/audit.php file:
'resolver' => [
'user' => App\Products::class,
'ip_address' => OwenIt\Auditing\Resolvers\IpAddressResolver::class,
'user_agent' => OwenIt\Auditing\Resolvers\UserAgentResolver::class,
'url' => OwenIt\Auditing\Resolvers\UrlResolver::class,
],
Related
I am trying to use this package to push notifications to users via OneSignal. However I needed to make a little change. My API serves two (related) apps and I have two OneSignal configs. I am trying to override its ServiceProvider (using this technique).
The ServiceProvider presents itself as follows
<?php
namespace NotificationChannels\OneSignal;
use Berkayk\OneSignal\OneSignalClient;
use Illuminate\Support\ServiceProvider;
use NotificationChannels\OneSignal\Exceptions\InvalidConfiguration;
class OneSignalServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*/
public function boot()
{
$this->app->when(OneSignalChannel::class)
->needs(OneSignalClient::class)
->give(function () {
$oneSignalConfig = config('services.onesignal');
if (is_null($oneSignalConfig)) {
throw InvalidConfiguration::configurationNotSet();
}
return new OneSignalClient(
$oneSignalConfig['app_id'],
$oneSignalConfig['rest_api_key'],
''
);
});
}
}
The behavior that I want to change is located in the line
$oneSignalConfig = config('services.onesignal');
As it assumes that my config/services.php has the following entry (stated in the doc) :
// config/services.php
...
'onesignal' => [
'app_id' => env('ONESIGNAL_APP_ID'),
'rest_api_key' => env('ONESIGNAL_REST_API_KEY')
],
...
Whereas I want to set my config/services.php as follows
// config/services.php
...
'onesignal' => [
'app1' => [
'app_id' => env('ONESIGNAL_1_APP_ID'),
'rest_api_key' => env('ONESIGNAL_1_REST_API_KEY')
],
'app2' => [
'app_id' => env('ONESIGNAL_2_APP_ID'),
'rest_api_key' => env('ONESIGNAL_2_REST_API_KEY')
],
],
...
And I want somehow to tell my ServiceProvider (through some kind of parameter) to either do
$oneSignalConfig = config('services.onesignal.app1');
OR
$oneSignalConfig = config('services.onesignal.app2');
But I didn't find any way to pass a parameter to the class, the boot function or the give method (and if I understood well I shouldn't even be doing that).
The only way I could think of is to create two classes that extend the OneSignalChannel::class
and duplicate code in the boot function so it becomes as follows :
public function boot()
{
$this->app->when(FirstOneSignalChannel::class)
->needs(OneSignalClient::class)
->give(function () {
$oneSignalConfig = config('services.onesignal.app1');
if (is_null($oneSignalConfig)) {
throw InvalidConfiguration::configurationNotSet();
}
return new OneSignalClient(
$oneSignalConfig['app_id'],
$oneSignalConfig['rest_api_key'],
''
);
});
$this->app->when(SecondOneSignalChannel::class)
->needs(OneSignalClient::class)
->give(function () {
$oneSignalConfig = config('services.onesignal.app2');
if (is_null($oneSignalConfig)) {
throw InvalidConfiguration::configurationNotSet();
}
return new OneSignalClient(
$oneSignalConfig['app_id'],
$oneSignalConfig['rest_api_key'],
''
);
});
}
The difference in the when provoking a difference in the config but it seems a lot of duplication and not extensible (what if I had three apps).
Should I use this method, or is there a way to pass a parameter to this ServiceProvider or is there another solution ?
https://stackoverflow.com/a/34224082/10371024
I could see what you need, but to pass parameter to boot method is not a good idea according to Laravel architecture. You may try to get what you want with using events as Vladislav suggested.
Integrating Firebase in "RESTFUL API" for the first time. The data had to sync into two databases i.e. MySQL and Firebase but the data didn't sync in Firebase.
Installation of firebase sync trait
composer require mpociot/laravel-firebase-sync
The configuration code to integrate Firebase into my API :-
'firebase' => [
'api_key' => 'AIzaSyCbOasfdsfdsfds',
'auth_domain' => 'restasdsaful-asdfs.firebaseapp.com',
'projectId' => 'restful-23aasdfsf60',
'messagingSenderId' => '8445794551330',
'database_url' => 'https://restful-sdfsdf23a60.firebaseio.com',
'secret' => 'mZ93YRkZ9ZErQvvtJyFKmRopsdfcwUEE5ImoMW89hWB',
'storage_bucket' => 'restfulas-23a60asda.appspot.com',
],
Note: for security reason I have changed values of configuration attributes.
Path where Firebase had been configured. config/services.php
The process that I applied for Syncronizing the Model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Mpociot\Firebase\SyncsWithFirebase;
class Demo extends Model
{
use SyncsWithFirebase;
protected $fillable = ['task','is_done'];
protected $visible = ['id', 'task', 'is_done'];
}
Please suggest a solution if there's any error in my code or any alternatives for this kind of problem. Thanks in Advance!!.
You can do like this:
use Firebase\Firebase;
class FirebaseController extends Controller
{
public function storeTask(Request $request){
$FIREBASE_URL = 'your_url_key;
$FIREBASE_SECRET = 'your_firebase_secret_key';
$fb = Firebase::initialize($FIREBASE_URL, $FIREBASE_SECRET);
$fb = new Firebase([ 'base_url' => $FIREBASE_URL, 'token' => $FIREBASE_SECRET,]);
$nodeSetContent = $fb->push('msg', $request->all());
return response()->json(['data'=>$nodeSetContent]);
}
}
you can take reference from this link (https://github.com/eelkevdbos/firebase-php)
I'm using Tymon JWT to generate my token in Laravel. I have followed the guide in Tymon's github site carefully to add my custom claims like so:
$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
JWTAuth::attempt($credentials, $customClaims);
I managed to generate a token after authenticating the user, but when I decode the token with JWT decoder, I only see the default claims, but not my custom claim.
You are using Tymon JWT version 1.0.0 maybe?
From Github Tymon JWT
For version 0.5.* See the WIKI for documentation.
Documentation for 1.0.0 is coming soon, but there is an unfinished guide here
Use
JWTAuth::customClaims(['foo' => 'bar'])->attempt(['login' => '', 'password' => '']);
You can using:
$store = [
'id' => 1,
'name' => 'Store1'
];
$token = JWTAuth::customClaims(['store' => $store])->fromUser($user);
And get info:
$storeData = JWTAuth::getPayload()->get('store');
I was able to add custom claims by putting them the getJWTCustomClaims method on my JWTSubject.
Example: if you want to specify a guard for your user class and put that information inside the token, you do the following :
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements JWTSubject
{
/**
* #return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* #return array
*/
public function getJWTCustomClaims()
{
return [
'guard' => 'admins', // my custom claim, add as many as you like
];
}
}
Be aware not to add too many custom claims because they will increase the size of the token.
Here is the version of Tymon-jwt that i use : "tymon/jwt-auth": "dev-develop#f72b8eb as 1.0.0-rc.3.2"
Hope this helps
I have used the Laravel Auditing plugin (http://www.laravel-auditing.com/docs/3.1) to log the all models changes.Am using different auth system but the Laravel Auditing
getLoggedInUserId()
using laravel core one so need to change that. i have forked this plugin and edited the function directly its worked. But i like to find another ways if you have idea share with me ?
protected function getLoggedInUserId()
{
try {
if (Auth::check()) {
return Auth::user()->getAuthIdentifier();
}
} catch (\Exception $e) {
return;
}
}
Unfortunately, until version 4 of the package, you couldn't change the user resolver without modifying the actual code.
However, from version 4 onwards, you can do so in the configuration file (config/audit.php).
The user resolver can be set in two ways.
As a Closure:
return [
'user' = [
'resolver' => function () {
return Auth::check() ? Auth::user()->getAuthIdentifier() : null;
},
],
];
As a FQCN:
return [
'user' = [
'resolver' => App\User::class,
],
];
TIP: You have to implement the OwenIt\Auditing\Contracts\UserResolver interface in the App\User class for this to work.
See the full documentation here.
I am writing a unit test in Laravel 5.0 and in my request class I am using a different bag to show the validation error messages.
I am using this in my file:
/* ExampleRequest.php */
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Support\Facades\Auth;
class ExampleRequest extends Request {
protected $errorBag = 'otherbag';
public function rules(){
return [
'my_field' => 'required'
];
}
}
In my test file, I am testing using this:
/* ExampleTest.php */
class ExampleTest extends TestCase {
public function testPostWithoutData(){
$response = $this->call('POST', 'url/to/post',[
'my_field' => ''
]);
$this->assertSessionHasErrors('my_field');
}
}
If I run the tests, it can't get the right assert and return this problem:
Session missing error: my_field
Failed asserting that false is true.
If I take out the $errorBag attribute from the request file, I have no problems.
I can give more details as needed.
You can get an alternate bag from the session store like this:
$myBag = $this->app('session_store')->getBag('otherBag');
$this->assertTrue($myBag->any());
However, Laravel does not use an alternate bag by default, so I'm assuming you're doing something in your code to register your App\Request::$errorBag with the session handler.
I don't know if you are setting your session elsewhere but I guess you may do something like:
$this->session(['foo' => 'bar']);
Before you can assert something in session. See testing helpers section for Laravel 5.0