How to access event manager in controller constructor ? when I call event manager in constructor , this error appears :
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for event
You don't have access to the service manager at this point, as it's injected once the object has been instantiated.
You could always move you code to be triggered onDispatch() rather than in the contructor:
/**
* Execute the request
*
* #param MvcEvent $e
* #return mixed
* #throws Exception\DomainException
*/
public function onDispatch(MvcEvent $e)
{
// do something here
// or you could use the events system to attach to the onDispatch event
// rather than putting your code directly into the controller, which would be
// a better option
return parent::onDispatch($e);
}
I would just use Events to attach what ever you need, rather than using the controller
Module.php
/**
* Initialize
*
* #param \Mis\ModuleManager
*/
public function init(ModuleManager $manager)
{
$events = $manager->getEventManager();
$sharedEvents = $events->getSharedManager();
$sharedEvents->attach(__NAMESPACE__, 'dispatch', function($e) {
/* #var $e \Zend\Mvc\MvcEvent */
// fired when an ActionController under the namespace is dispatched.
$controller = $e->getTarget();
$routeMatch = $e->getRouteMatch();
/* #var $routeMatch \Zend\Mvc\Router\RouteMatch */
$routeName = $routeMatch->getMatchedRouteName();
// Attach a method here to do what you need
}, 100);
}
Related
In my application, there is a 'status' column in the 'users' table. Which indicates the user activeness. Now I want to check the activeness of the user before login to the system and give a message if he is deactivated. How to do this? There are several answers here, but I cannot make this work with the help of those answers.
This is my LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
Create a middleware class to check the status column. For example:
<?php namespace App\Http\Middleware;
use Closure;
class CheckStatusMiddleware {
/**
* Run the request filter.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$user = User::where('email', $request->input('email'))->firstOrFail();
if (!$user->active)
{
return redirect('home');
}
return $next($request);
}
}
Then register the class and apply it to the necessary route(s).
See Middleware for more information.
You can use authenticated() method.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;
class LoginController extends Controller
{
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/dashboard';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
/**
* The user has been authenticated.
*
* #param \Illuminate\Http\Request $request
* #param mixed $user
* #return mixed
*/
protected function authenticated(Request $request, $user)
{
// Check status
if ($user->status == 'inactive') {
$this->logout($request);
// Send message
throw ValidationException::withMessages([
$this->username() => [__('Your status is inactive')],
]);
}
}
}
I am trying to isert data in mysql using laravel, while I am getting the error ErrorException (E_NOTICE)
Trying to get property of non-object, where is the problem I dont know please help me.
my controller code is PublicationController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\publication;
use Auth;
class PublicationController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
return view('publications');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
publications::create([
'user_id' => Auth::user()->id,
'title' => request('title'),
'status' => request('status'),
'year' => request('research_area')
]);
return 'inserted';
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
While model code is given publication.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class publication extends Model
{
//
protected $fillable = ['title','status','year'];
}
The code of my route is given.
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('education', 'EducationController#index');
Route::post('edu', 'EducationController#store');
Route::get('publications','PublicationController#index');
Route::post('pub','PublicationController#store');
The error is given Class ErrorException (E_NOTICE)
Trying to get property of non-object please help if any one know where is the problem
Consider placing PublicationController behind authentication middleware:
class PublicationController extends Controller
{
...
public function __construct()
{
$this->middleware('auth');
}
...
}
You can also use route groups:
Route::middleware(['auth'])->group(function () {
// your routes
});
If Auth::user() is null then Auth::user()->id will give you the exception you mentioned. Placing the routes or controller behind the middleware should solve this.
Edit
This assumes you are using Laravel 5.6 https://laravel.com/docs/5.6. This should work for 5.5 and 5.7.
Finally I found the answer of my question by just including 'user_id' in my model fillable arry and the above code works properly.
İ think you are not logged in so you get error when you try to get Auth::user()-id
Add this contractor to your class i think it should work for you
public function __construct(){
$this->middleware('auth');
}
I am using ajax for ratings. Rating successfully but return response with html code above the json. And it is because of send mail function.
The this code alwasy attached when return response and may be it was from send mail function.
When I am removing Mail function it will return proper result and its working well.
If i were in your place i will work with jobs.
So Here is how it goes
php artisan make:job SendingEmail
App\Jobs\SendingEmail.php
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Mail;
class SendingEmail implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
protected $admin_email;
protected $email_data;
/**
* Create a new job instance.
*
* #return void
*/
public function __construct($admin_email,$email_data)
{
$this->email_data = $email_data;
$this->admin_email = $admin_email;
}
/**
* Execute the job.
*
* #return void
*/
public function handle()
{
Mail::to($this->admins_email)->send(new RateNotification($this->email_data));
}
}
App\Jobs\SendingEmail::dispatch($podcast);
In Your Controller add this
App\Jobs\SendingEmail::dispatch($admin_email,$email_data);
I have mysql tables:
Balance
id | client_id | balance
And
Payments**
id | payment_date | amount | foreign key -> balance_id
What methods are used to update balance when I store payment amount?
Inside your payments model, you can create an event handlers like so:
/**
* The event map for the model.
*
* #var array
*/
protected $dispatchesEvents = [
'created' => \App\Events\PaymentCreated::class,
];
Then you can create an event like so:
PaymentCreatedEvent
<?php
namespace App\Events;
use App\Models\Payments;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
class PaymentCreatedEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $payments;
/**
* Create a new event instance.
*/
public function __construct(Payments $payments)
{
$this->payments = $payments;
}
/**
* Get the channels the event should broadcast on.
*
* #return Channel|array
*/
public function broadcastOn()
{
return new PrivateChannel('channel-name');
}
}
Then you can create a listener to create the balance:
PaymentCreatedListener
<?php
namespace App\Listeners;
use Illuminate\Support\Facades\Mail;
use App\Events\PaymentCreatedEvent;
class PaymentCreatedListener
{
/**
* Create the event listener.
*/
public function __construct()
{
}
/**
* Handle the event.
*
* #param PaymentCreatedEvent $event
*/
public function handle(PaymentCreatedEvent $event)
{
// Insert in to the balance table here
}
}
Then inside your eventserviceprovider.php add
/**
* The event listener mappings for the application.
*
* #var array
*/
protected $listen = [
'App\Events\PaymentCreatedEvent' => [
'App\Listeners\PaymentCreatedListener',
],
];
To listen to your event. You will need to create the insert statement inside the listener... But you get the idea.
In payment issues i think you must handle transaction and check that all inserts/updates run successfully.
You can one of approaches:
1.
In your payment model:
static function boot() {
static::created(function($payment){
//update balance here
}
}
2.
In your controller or other class:
DB::beginTransaction();
try{
//insert payment row
//update balance
DB::commit();
}
catch (\Exception $e){
DB::rollback();
}
I've created a new XmlResponseFormatter and now I want to change the rootTag.
class newXmlResponseFormatter extends XmlResponseFormatter
{
/**
* #var string the name of the root element.
*
*/
public $rootTag;
public function __construct($rootTag) {
parent::__construct();
$this->rootTag = $rootTag;
}
}
From a controller I set that value:
$xmlFormater = new newXmlResponseFormatter('newRootTag');
In the controller that value is available, and it sets in $rootTag but it threw the following exception:
exception 'yii\base\InvalidConfigException' with message 'Missing required parameter "rootTag" when instantiating "app\components\override\newXmlResponseFormatter".' in /var/www/html/Admin/vendor/yiisoft/yii2/di/Container.php:451
Does anyone know what can be a problem?
Thanks in advance!
First parameter in XmlResponseFormatter is $config, because XmlResponseFormatter extends Object class. You are violated liskov substitution principle.
You should rewrite your constructor like this:
class newXmlResponseFormatter extends XmlResponseFormatter
{
/**
* #var string the name of the root element.
*
*/
public $rootTag;
/**
* newXmlResponseFormatter constructor.
*
* #param string $rootTag
* #param array $config
*/
public function __construct($rootTag, $config = [])
{
$this->rootTag = $rootTag;
parent::__construct($config);
}
}
In yii2 you should call parent constructor after your code, and call parent init before your code.
$config need for simple configure model like this:
new newXmlResponseFormatter(['rootTag' => 'newRootTag']);