How to access data of one function to another in laravel - php

Okay the issue is something like this
I have a function in AController
public function index()
{
$store = Store::(query)(to)(rows)->first();
return view('store.index', compact('store'));
}
Now in the same controller I have another function
public function abc()
{
return view('store.abc');
}
Now to this function I also want to send the compact('store') to the view abc I can just add the query again in the abc() function but that would be lazy and make performance issues. Is there a way that I can access $store object in other functions too?

If I understand you correctly you want to access the same query from two places. So extract getting stores to another method like
private function store()
{
$minutes = 10; // set here
return Cache::remember('users', $minutes, function () {
return Store::(query)(to)(rows)->first();
});
}
Additionally I have cached the query. So it get executed once at a defiened time.
Then access it from other two methods like,
public function index()
{
$store = $this->store();
return view('store.index', compact('store'));
}
public function abc()
{
$store = $this->store();
return view('store.abc', compact('store'));
}

class StoreController extends Controller
{
public function index()
{
return view('admin.store',['data' => $this->getSetting()]);
}
public function getStoreData()
{
//get your data here, for example
$data = Store::where('status',1)->first();
//get all data
//$data = Store::all();
return ($data);
}
}

Try the following. Not testing but it should work for you.
class AController
{
public function getStore()
{
$store = Store::(query)(to)(rows)->first();
return compact('store');
}
public function index()
{
return view('store.index', $this->getStore());
}
public function abc()
{
return view('store.abc', $this->getStore());
}
}

Related

Laravel php - Do something at the beginning and end of function

I'm trying to do something at the beginning and end of each function.
instead of doing so
public function beforeEveryFunctionCore()
{
//something
}
public function afterEveryFunctionCore()
{
//something
}
public function newFunction1(Request $request)
{
$this->beforeEveryFunctionCore();
//function core
$this->afterEveryFunctionCore();
return $something;
}
public function newFunction2(Request $request)
{
$this->beforeEveryFunctionCore();
//function core
$this->afterEveryFunctionCore();
return $something;
}
and so on repeated..(boring)
I would like something like this.
public function beforeEveryFunctionCore()
{
//it does something that is called automatically
}
public function afterEveryFunctionCore()
{
//it does something that is called automatically
}
public function newFunction1(Request $request)
{
//function core
return $something;
}
public function newFunction2(Request $request)
{
//function core
return $something;
}
I know I can do something before every API call with middleware and with construct.
But in this case I talk about any function even those in traits.
How do you think it can be done?

Create DB record return wrong data types Laravel 5.8

In my model I have functions for create and find records.
Model
use Illuminate\Database\Eloquent\Model;
class Charge extends Model
{
use ChargeMutator;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->request = $attributes;
}
public function add() {
$result = self::create($this->request);
return $result;
}
public function find($id) {
$record = self::find($id);
return $record;
}
}
And I have a mutator to mutate the values.
<?php
trait ChargeMutator
{
public function getCostAttribute($value)
{
return $this->attributes['cost'] = // call function A;
}
public function getTotalCostAttribute($value)
{
dd(gettype($value));
return $this->attributes['total_cost'] = // call function A;
}
public function setCostAttribute($value)
{
return $this->attributes['cost'] = // call function B;
}
public function setTotalCostAttribute($value)
{
return $this->attributes['total_cost'] = // call function B;
}
}
Controller
class ChargesController extends Controller
{
use ValidateCreditNoteCharges, Messages, ApiResponser;
public function addCharge(Request $request)
{
// $this->validateAddCharge($request);
$credit_note_charge = new Charge($request->all());
$get_result = $credit_note_charge->add();
return $this->createdResponse($get_result);
}
}
the $request is like this
{
"name":"TEST",
"quantity":1,
"cost":56.00,
"total_cost":56.00
}
The Problem is:
when I dd(gettype($value)); in getTotalCostAttribute
from the add() function the type of total_cost value is string
from the find() function the type of total_cost value is integer
in the database the data type for total_cost is int(10)
I am not sure why is the type of the return values casted into strings when use create()
I have searched for this for 3 hours now and couldn't find a solution. i need the data type correctly because accoriding to the data type i do different calculations in my calling functions A and B

Laravel - How to return data from two repositories

I'm trying to return two methods at once in the find function
public function find($id)
{
return AddRepository::findOrFail($id) &&
AddMeRepository::findOrFail($id);
}
public function find($id)
{
var result = [];
result['addRepository'] = AddRepository::findOrFail($id);
result['addMeRepository'] =AddMeRepository::findOrFail($id);
return result;
}
public static function find($id)
{
return array(AddRepository::findOrFail($id) ,AddMeRepository::findOrFail($id));
}
when you call method
list($add,$addme)=YourClass::find($id);
you can use $add and $addme variables.

Cloning $this to do chaining. Is it a bad idea?

I am having the following class:
class StuffDoer{
public function __construct(Dep1 $dep, Dep2 $dep2, array $array){
$this->dep = $dep;
$this->dep2 = $dep2;
$this->array = $array;
}
public function genericDoStuff($param){
// Do stuff here...
}
public function doStuffForMark(){
return $this->genericDoStuff('Mark');
}
public function doStuffForTim(){
return $this->genericDoStuff('Tim');
}
public function doStuffForAlice(){
return $this->genericDoStuff('Alice');
}
}
After some months, I am asked to make the method genericDoStuff($param), along with all the methods that depend on it, use an extra parameter in a single part of the application. Instead of changing the signature on every single method that depends on genericDoStuff, I ended up with the following:
class StuffDoer{
public function __construct(Dep1 $dep, Dep2 $dep2, array $array){
$this->dep = $dep;
$this->dep2 = $dep2;
$this->array = $array;
}
public function forParameter($param){
$self = clone $this;
$this->param = $param;
return $self;
}
public function genericDoStuff($param){
if($this->param !== null){
// Do stuff by taking param into account
} else {
// Do stuff stuffdoer does
}
}
public function doStuffForMark(){
return $this->genericDoStuff('Mark');
}
public function doStuffForTim(){
return $this->genericDoStuff('Tim');
}
public function doStuffForAlice(){
return $this->genericDoStuff('Alice');
}
}
That way, I am able to do this in the single point of the application:
$myStuffDoer = $serviceContainer->get('stuff_doer');
$myStuffDoer->forParameter('AAAARGHITBURNSGODHELPME')->doStuffForMark();
// Future usages of $myStuffDoer are unaffected by this!
So my question is this: Is this considered a bad practice for any reason?

Codeigniter with datamapper save error

So I was trying to make a CRUD for my app. I have setup a controller, like this:
class Clients extends CI_Controller {
public function __construct() {
parent::__construct();
session_start();
$this->c = new Client();
$this->u = new User();
}
function index() {
$data['current_view'] = 'client_view';
$data['header'] = 'Меню клиентов';
$data['clients'] = $this->getClients();
$this->load->view('main_view',$data);
}
function getClients() {
$this->u->where('username',$_SESSION['username'])->get();
$c = $this->c->where('user_id',$this->u->id)->get();
return $c;
}
function delClient() {
$this->c->where('client_id', $this->uri->segment(3))->delete();
$this->c->skip_validation()->save();
$this->index();
}
}
However, when I'm trying to perform a delete on a client, i get a db error:
You must use the "set" method to update an entry.
Filename: C:\OpenServer\domains\localhost\system\database\DB_active_rec.php
Line Number: 1174
What might be the cause of this? I found a similar question here, but I don't think that's the case.
EDIT: Client model:
class Client extends DataMapper {
public $has_one = array('user');
public function __construct($id = NULL) {
parent::__construct($id);
}
}
you have not passed the uri segment to the function delClient() and this is your model right...
function delClient($id) {
//$id is the value which you want to delete
$this->c->where('client_id', $id)->delete();
$this->c->skip_validation()->save();
$this->index();
}

Categories