Can I use a constructor in Laravel's Form Request class? - laravel

I'm trying to use a constructor inside my CreateLeadRequest class, but it seems to be failing.
class CreateLeadRequest extends FormRequest
{
private $dealer;
public function __construct() {
parent::__construct();
$this->dealer = Dealer::findOrFail($this->dealer_id);
}
}
$this->dealer_id is coming in as null. I can use it inside prepareForValidation and other functions just fine, so why is it coming in as null inside the constructor?

Related

Pass Customer FormRequest to GET in Laravel

I'm curious is that possible to pass (as type-hinted) of custom class that extends FormRequest to be passed in to action within GET request ?
for example:
at routes/api.php
Route::get('/schema', '\App\Http\Controllers\TestController#getSchema');
then I have App\Http\Requests\SchemaRequest.php
and at controller, I want get this request from route within GET method.
class TestController extends Controller {
public function getSchema(\App\Http\Requests\SchemaRequest $request) {
// do other stuff here
}
}
I've tried to look deeper and doing some hack but nothing success yet?
Is that possible?
Any input would be appreciated, and thanks for reading
How about this workaround?
Route::get('/schema', 'TestController#getSchema',namespace =>'App\Http\Controller');
class TestController extends Controller {
public function getSchema(Request $request) {
// do other stuff here
}
}

How to write a custom function in a model?

There is a model data:
class Order extends Model
{
}
How to write a custom method inside the Order class so that it can be called in constructor like this:
Order::myMethod()
Order->myMethod()
Where myMethod is:
public function myMethod() {
return DB::query(<SQL QUERY>);
}
Purpose is to move SQL queries inside model's class, that don't mess this code in controllers.
Rather create a custom function in Model, You can use traits to achieve the desired output.
Please follow either steps:-
https://medium.com/#kshitij206/traits-in-laravel-5db8beffbcc3
https://www.conetix.com.au/blog/simple-guide-using-traits-laravel-5
Guess you are asking about the static functions:
class Order extends Model {
public static function myMethod() {
}
}
and you can call it anywhere like
Order::myMethod();
You can achieve the desired behavior using magic methods __call and __callStatic
if your real method is static you can use __call() to intercept all "non static" calls and use it to call the static and use __callStatic to forward the calls to a new instance to that class .
Your methods should be always static because if a non static method exists and you are calling it statically php raises an error
Non-static method Foo::myMethod() should not be called statically
No problem if your method is static
class Order extends Model {
public static function myMethod() {
return static::query()->where(...)->get(); // example
}
public function __call($name, $arguments) {
return forward_static_call_array([__CLASS__, $name], $arguments);
}
public static function __callStatic($name, $arguments) {
return call_user_func_array([app(__CLASS__), $name], $arguments);
}
}
(new Order())->myMethod();
Order::myMethod();
I can't understand your exact problem is. but if you are using laravel, then you can write custom method inside the ABC model like this
class ABC extends Model
{
//here is your fillable array;
public function abc()
{
//Here is your Eloquent statement or SQL query;
}
}
just call this abc() method inside the controller like this
use ABC;
class AbcController extends Controller
{
private $_abc; // it is private variable
// this is constructor
public function __construct(ABC $abc)
{
$this->_abc= $abc;
}
public function abcMethod()
{
$this->_abc->abc();
}
}
Thanks
I don't believe I'm understanding your intention. You've stated:
Purpose is to move SQL queries inside model's class, that don't mess this code in controllers.
Why does the Order->myMethod() need calling inside the constructor? If you're trying to design your data access layer to work efficiently, you can use data repositories.

How to use different method of a controller in laravel application

In my laravel application i should use some create and update method of some controller in another controller
According to my search is not a good thing to call a method from controller in another
I cant see the why don't call a controller method in another controller
I'm doing this way :
class Controller extends BaseController
{
protected $variable;
public function __construct()
{
$this->variable = "Hello";
}
}
and
class ClientController extends Controller
{
public function __construct()
{
parent::__construct();
}
}
The __constructor is a magic method of class. It calls when you trying to create instance of class. So there is no way to use constructor without creating an instance or extendeding from another class. If you have a common code in different classes there a best way to use traits. thats give you an opportunity to include your trait and use methods ,making your code beutiful , flexible , readable following principes DRY,KISS.
you can create a base class with constructor and extend other controller of it
or you can put your code in to Http\Controllers\controller.php ('main controllers constructor')
also you can use trait

Laravel: use extended controller or Traits or something else?

To maintain my Laravel application and save myself from a lot of duplicate code I have made the following solution:
BaseController
class BaseController extends Controller
{
public function get($id){
return $this->baseService->get($id);
}
public function getAll(){
return $this->baseService->getAll();
}
}
BaseService
class BaseService
{
protected $model;
public function __construct($model){
$this->model = $model;
}
public function get($id){
return response()->json($this->model->where('id', $id)->first());
}
public function getAll()
{
return $this->model->get();
}
}
MyController
class MyController extends BaseController
{
protected $model;
protected $baseService;
public function __construct(){
$this->model= new Model();
$this->baseService = new BaseService($this->model);
}
/**
* This controller has all the functionality from BaseController now
*/
}
What I'm wondering if this is a good method. Should I stick with this or should I use a different approach? I've heard about Traits but not sure if they are doing the same thing. It's Laravel 5.5 I'm using.
Yes, traits are used to move methods out of a controller regularly. A good example that the Laravel framework uses is the ThrottlesLogin trait. Take a look at https://github.com/laravel/framework/blob/5.5/src/Illuminate/Foundation/Auth/ThrottlesLogins.php#L20
to see how the methods are moved outside of a controller but can be still accessed by importing the trait using the use keyword.
While traits would work for your use case I wouldn't use them here for the functionality you are looking for. I would use the repository pattern. It would better separate your code and make it more reusable.
Take a look at https://bosnadev.com/2015/03/07/using-repository-pattern-in-laravel-5/ for more information on the repository pattern. Basically, you would separate your code into a separate repository and use Laravel's built in IoC to inject the repository into your controller.
MyController
class MyController extends Controller
{
protected $repo;
public function __construct(MyRepository $myRepository)
{
$this->repo = $myRepository;
}
public function index()
{
$myStuff = $this->repo->all();
}
// you can also inject the repository directly in the controller
// actions.
// look at https://laravel.com/docs/5.5/controllers#dependency-injection-and-controllers
public function other(MyRepository $repo)
{
$myStuff = $repo->all();
}
}
This is the perfect use case for a Trait. Traits are intended for reusable functions. They're super simple to implement, and won't take more than a few minutes to change what you have.
Here is a great article on them: https://www.conetix.com.au/blog/simple-guide-using-traits-laravel-5

Laravel abstract class auto injection

Laravel auto injects abstract class , but when there is another parameter with abstract class, Laravel ignore it and hence, getting error.
public interface PostRepository {
public function getPostById($id)
}
class EloquentPost implements PostRepository{
public function getPostById($id){
return Post::find($id);
} }
Its working fine when I use it like:
class Controller PostController {
private $post;
public function __construct(PostRepository $post)
$this->post = $post;
}
But when I use it like
class Controller PostController {
private $post;
public function __construct($someOtherParam, PostRepository $post)
$this->post = $post;
}
then Laravel show error.
Laravel is unable to determine what should be injected as the first parameter to the controller's constructor as you have no type hint for that parameter.
If that $someOtherParam is something that should come in the URL, you will be able to have that injected in controller's action method to which given route points, but not in the constructor.

Resources