Laravel Controller member variable - laravel

Is there any possibility in laravel to keep the state of the controller object?
In every example I found, the controller looks the following way:
class MyController extends Controller {
public function getView(){ //return the view }
public function postData() { //save the data }
}
What I would do is to call a service which loads specific data from my data base and return it to the view. In the example above this should be done within the getView() function. What if I need the same data in my postData() function.. Then I have to make another database call in the postData function. It is not possible to have a member variable in 'MyController' and to load the data only once for the class because of routing in laravel. When I call via routing the getView function I get another instance of MyController than I get if I call postData. Is there a possibility to call a specific function only once for the whole controller and to get access to this values from all the functions within the controller?

Is there a possibility to call a specific function only once for the
whole controller and to get access to this values from all the
functions within the controller?
As per my understanding it it not possible. Actually any function of controller is being called via routes. When your any route has been called every time the new object of controller is being created. But it has other way of round. You can use Cache. You can implement it as below:
Call to your specific function of controller.
Get the data from the database.
Store it in Cache for other functions.
In other functions check is data available in Cache? then get from Cache else call your database function to get the data.
Simply in coding as below:
Use Cache;
class MyController extends Controller {
public function getView(){
$data = call_to_database_and_returned_data();
Cache::put('data',$data,120);
return the view
}
public function postData() {
$data = null;
if(Cache::has('data')) {
$data = Cache::get('data');
} else {
$data = call_to_database_and_returned_data();
Cache::put('data',$data,120);
}
}
}
Syntax Description:
Cache::put('name_to_save_data',$your_variable_to_save,for_number_minutes);

Related

How can I encrypt all ids in URL (laravel 9) using repository pattern

I need to do all url ids encrypted like :
user/edit/1
items/edit/35
posts/details/52
to below url path
user/edit/gd43dfrg
items/edit/sdfg4343
posts/details/fasdf23423
there is lots of areas in repository pattern like UserRepository , UserController blade files and in controllers that id used url ('items/edit/2')
however also in controller some function are passed by objects like
public function itemedit(Items $items)
I tried
$encrypt_val = Crypt::encrypt($value) and $decrypt_val = Crypt::decrypt($encrypt_val );
but I need to do it all over app. There is any short way or Middleware function to do it using repository pattern ?
The proper way to do this would be like so:
Use any boot function of a service provider (e.g. RouteServiceProvider) to define how a route parameter should be invoked:
public function boot()
{
// Bind any `{order}` route parameter such that it decodes the value before retrieving the order.
Route::bind('order', function ($value) {
return User::query()->where('id', $this->yourDecodeFunction($value))->firstOrFail();
});
}
Now when you create urls like route('orders.show', yourEncodeFunction($order->id)) from a route
Route::get('/orders/{order}', /*...*/);
your controller method will receive the expected order in its signature i.e.
public function show(Request $request, Order $order) {
//
}
To improve this code, you can define the getRouteKey() function (part of the UrlRoutable trait) on your Eloquent model to simplify the creation of your routes so that you can call route('orders.show', $order):
// App/Models/Order.php
public function getRouteKey()
{
return yourEncodeFunction($this->getKey());
}
This will make sure that the route parameter is automatically identified when you pass the complete object to the route call (if you don't override this function yourself it uses the model's primary key).
https://packagist.org/packages/hashids/hashids might be a good package for you if you just want to obfuscate some of the url (note that this package is an 'encoder' and not an 'encrypter').

Returning same variable to every controller in laravel

I need to send the same result to almost every view page, so I need to bind the variables and return with every controller.
My sample code
public function index()
{
$drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
$locations = Location::get();
return view('visitor.index', compact('drcategory','locations'));
}
public function contact()
{
$drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
$locations = Location::get();
return view('visitor.contact', compact('drcategory','locations'));
}
But as you see, I need to write same code over and over again. How can I write it once and include it any function whenever I need?
I thought about using a constructor, but I cannot figure out how I can implement this.
You are able to achieve this by using the View::share() function within the AppServicerProvider:
App\Providers\AppServiceProvider.php:
public function __construct()
{
use View::Share('variableName', $variableValue );
}
Then, within your controller, you call your view as normal:
public function myTestAction()
{
return view('view.name.here');
}
Now you can call your variable within the view:
<p>{{ variableName }}</p>
You can read more in the docs.
There are a few ways to implement this.
You can go with a service, a provider or, like you said, within the constructor.
I am guessing you will share this between more parts of your code, not just this controller and for such, I would do a service with static calls if the code is that short and focused.
If you are absolutely sure it is only a special case for this controller then you can do:
class YourController
{
protected $drcategory;
public function __construct()
{
$this->drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
}
// Your other functions here
}
In the end, I would still put your query under a Service or Provider and pass that to the controller instead of having it directly there. Maybe something extra to explore? :)
For this, you can use View Composer Binding feature of laravel
add this is in boot function of AppServiceProvider
View::composer('*', function ($view) {
$view->with('drcategory', DoctorCategory::orderBy('speciality', 'asc')->get());
$view->with('locations', Location::get());
}); //please import class...
when you visit on every page you can access drcategory and location object every time
and no need to send drcategory and location form every controller to view.
Edit your controller method
public function index()
{
return view('visitor.index');
}
#Sunil mentioned way View Composer Binding is the best way to achieve this.

Where should I be saving a model in Laravel MVC?

I'm trying to get a more concrete understanding of MVC and keeping the controller layer as thin as possible.
One thing I keep asking myself is "Where should I call modelname->save()?"
Looking at the Laravel documentation, they set data to the model and call save in the controller which doesn't seem right...
<?php
namespace App\Http\Controllers;
use App\Flight;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class FlightController extends Controller
{
public function store(Request $request)
{
// Validate the request...
$flight = new Flight;
$flight->name = $request->name;
$flight->save();
}
}
This is quite a simple example and might be why they do it all in the controller.
From my understanding and everything I've been reading, all business logic should sit inside the model, the controller is responsible for "traffic control" between the view and the model.
So would I be calling save inside the model itself? or should I be using a service layer?
Here is my current problem with example data.
I am updating the status of a model. The row already exists in the DB. I use PATCH /route/ to get to the controller method. From there I get the model.
class TimecardController extends Controller {
...
public function markAsPass(Request $request, $id) {
$test = Test::findOrFail($id);
//I don't think this is the corect way
//$test->status = "passed";
//$test->markedBy = "Teacher123";
//$test->save();
$test->passed();
...
return redirect($redirect_url);
}
}
class Test extends Model {
...
public function passed() {
$this->status = "passed";
//would I call save here?
//$this->save();
}
}
Do I take an approach like above? Or do I create a service layer where I would use the model instance to call the model functions and then call save on the model?
//in service class
public function makeTestAsPassed($test){
$test->passed();
$test->save();
}
Please let me know if any claification is needed.
You’re right in that business logic belongs in models. If you take a “resourceful” approach to your applications (in that you create controllers around entities) then you’ll find that your controller actions seldom call more than one model method.
Instead of calling save(), you can call create() and update() methods on your model. In your store() controller action, you can create a new entity with one line like this:
public function store(CreateRequest $request)
{
$model = Model::create($request->all());
}
And update an existing model in an update() action like this:
public function update(UpdateRequest $request, Model $model)
{
$model->update($request->all());
}
When it comes to business logic, you can call other methods on your models, too. To use resourceful controllers, you don’t have to have a model that relates to a database table.
Take shipping an order. Most people would be tempted to put a ship() method in an OrderController, but what happens when you ship an order? What entity could shipping an order result in? Well, you’d be creating a shipment, so that could instead be a store() method on an OrderShipmentController. This store() method could then just call a ship() method on your Order model:
class OrderShipmentController extends Controller
{
public function store(ShipOrderRequest $request, Order $order)
{
$order->ship();
}
}
So as you can see, with resourceful controllers and route–model binding, you can have “skinny controllers” with your application’s business logic living in your models.
MVC is designed for ease of maintenance.
The approach you don't recognize as "good" is the proper approach. All data handling related to business logic goes in the controller. Otherwise, a different coder will be confused as he/she would not find the data manipulation logic in the controller code.
Your thin controller goal defeats MVC.
Also note the model code is purposed to be thin as it is a place to define the database schema as mirror image to the database tables.
MVC is not object oriented abstration. MVC is a structure for code maintenance uniformity.

My Own Controller Method in Auth Facade in Laravel 5.1

I want to add my own controller method to Auth Facade in Laravel
auth()->user()->ownControllerMethod()
How can we do that ?
In your example, you'd actually be adding a method to the User model. (User.php)
public function my_method() {
// code here
}
EDIT:
Per your comment, lets say your route is mapped to the index() method in your UsersController, you could do this:
public function index()
{
// some code
$this->doSomething();
}
protected function doSomething()
{
// some code
// return data
}
But it really depends what this method is meant to do. There's lots of different ways to break up your code. And depending on the size of your project, your User model maybe a fine place.

How to Call a controller function in another Controller in Laravel 5

im using laravel 5.
I need to call a controller function but this should be done in another controller.
I dont know how to do this
public function examplefunction(){
//stuff
}
And i have a Route for this function, so at
public function otherfunctioninothercontroller(){
// I need examplefunction here
}
how Can i do this?
1) First way
use App\Http\Controllers\OtherController;
class TestController extends Controller
{
public function index()
{
//Calling a method that is from the OtherController
$result = (new OtherController)->method();
}
}
2) Second way
app('App\Http\Controllers\OtherController')->method();
Both way you can get another controller function.
If they are not in the same folder, place use namespace\to\ExampleClass; on top of your file, then you are able to instantiate your controller.
You can simply instantiate the controller and call the desired method as follows
FirstController.php:
namespace App\Http\Controllers;
class FirstController extends Controller {
public function examplefunction() {
// TODO: implement functionality
}
}
SecondController.php:
namespace App\Http\Controllers;
class SecondController extends Controller {
public function test() {
$object = new FirstController();
$object->examplefunction();
}
}
Now, after i've answered the question, i would like to add the following comment:
Controllers are classes, all rules that applies to normal classes can be applied to them
However, instantiating a controller directly inside another controller to call a desired method signifies a problem in your design for the following 2 reasons:
A controller cannot obtain an instance of another controller directly
Controller should contain as little business logic as possible, and if possible none
The closest possible solution to what you want (WITHOUT BREAKING MVC) is to make an HTTP request to the route that points to the desired method (using cURL, for example) and read the response as the returned data
But this still doesn't make much sense in this scenario because after all you're making an HTTP request from a method in a controller in your project on your server to a method in a controller in your project on your server, seems like unnecessary overhead, right ?
As i said earlier, a controller should contain as little business logic as possible because the logic should stay inside specialized classes (commonly known as Service Classes), and when a processing is requested the controller simply delegates the job of processing to the appropriate service class which does the processing and returns the results to the controller which in turn sends it back as a response
Now imagine if you've the following scenario:
We've got an application that consists of 3 functionalities:
A user can register an account from web application
There's a mobile application that talks to an API to register a user
There's an admin panel, which he can use to add new user
Obviously you need to create 3 controllers, but those controllers contains repeated logic, would you copy/paste the code everywhere ?
Why not encapsulate this logic inside a service class and call it from the controller when needed ?
Let's say I have Controller1 and Controller2. I want to call a function of Controller1 from inside a function placed in Controller2.
// Controller1.php
class Controller1 {
public static function f1()
{
}
}
And on the other controller:
// Controller2.php
use App\Http\Controllers\Controller1;
class Controller2 {
public function f2()
{
return Controller1::f1();
}
}
Points to be noted:
f1() is declared static
A call to a controller from inside another controller is a bad idea. There is no sense of meaning of controllers then. You should just redirect to web.php to save safe whole architecture like this:
class MyController {
public function aSwitchCaseFunction(Request $requestPrm){
...
//getting path string from request here
...
switch($myCase){
case CASE_1:
return redirect()->route('/a/route/path');
....
}
}
}

Resources