Laravel cookie in compose function - php

To build my menu i have a file Providers/ViewComposerServiceProvicer.php . in this file I have:
public function boot()
{
$this->composeNavigation();
}
public function composeNavigation()
{
view()->composer('front.layouts.menu', function ($view) {
$view->with('menuItems', \App\MenuItem::orderBy('priority', 'asc')->get());
});
}
What i want is add a where query based on a Coockie value like:
$brand = $request->cookie('brand');
// if value not set use default value.
if($brand == null)
{
$brand = 1;
}
view()->composer('front.layouts.menu', function ($view) {
//extra where function
$view->with('menuItems', \App\MenuItem::Where('brand','=',$brand)->orderBy('priority', 'asc')->get());
});
How can I get the coockie value in the compose function? Is there a special way to pass Request to my composeNavigation function?
EDIT i got it working but i cant access $brand in view()->composer(), if i copy my code inside the function i cant access request
My updated code :
public function boot(Request $request)
{
$this->composeNavigation($request);
}
public function composeNavigation(Request $request)
{
$coockieValue = $request->cookie('brand');
// if value not set use default value.
if($coockieValue == null)
{
$coockieValue = null;
}
$brands = \App\Brand::orderBy('priority', 'asc')->get();
foreach($brands as $brand){
if($brand->id == $coockieValue){
$brand->menuActive = true;
}
else{
$brand->menuActive = false;
}
}
view()->composer('front.layouts.menu', function ($view) {
$view->with('brandItems',$brands );
});
}

Related

How to call a named function as a callback in laravel?

I got two functions in my model:
function getPersonsByGroup($groupId, $callback) {
$group = StutGroup::where('stg_id', $groupId)->get();
$persons = [];
foreach($group as $gr) {
foreach($gr->students as $stud) {
$persons[] = $stud->person;
}
}
return $callback(collect($persons));
}
function joinStudentsToPersons($person) {
return $person->each(function ($pers) {
$pers->student = \DB::connection('pgsql2')->table('students')->where('stud_pers_id', $pers->pers_id)->get();
});
}
I'm trying to call the function getPersonsByGroup in my controller passing the reference to the callback as follows:
$students = $studGroup->getPersonsByGroup($request->group, $studGroup->joinStudentsToPersons);
But if I pass an anonymous function to the getPersonsByGroup everything works well:
$students = $studGroup->getPersonsByGroup($request->group, function($person) {
return $person->each(function ($pers) {
$pers->student = \DB::connection('pgsql2')->table('students')->where('stud_pers_id', $pers->pers_id)->get();
});
});
What am I doing wrong?
The solution to your problem, if you want to keep this kind of structure, is to make the method return the closure like so:
function joinStudentsToPersons() {
return function ($person) {
$person->each(function ($pers) {
$pers->student = \DB::connection('pgsql2')->table('students')
->where('stud_pers_id', $pers->pers_id)
->get();
});
};
}
And then call it like:
$students = $studGroup->getPersonsByGroup($request->group, $studGroup->joinStudentsToPersons());

How to check returned value to which function it belogns

Say I have to similar function :
public function auth(){
return $someResponse;
}
public function collect(){
return $someOtherResponse
}
Question : When one of the response get passed to another class, is there any way to check which function returned the response ?
In a purely object-oriented way, wanting to attach information to a value is akin to wrapping it into a container possessing context information, such as:
class ValueWithContext {
private $value;
private $context;
public function __construct($value, $context) {
$this->value = $value;
$this->context = $context;
}
public value() {
return $this->value;
}
public context() {
return $this->context;
}
}
You can use it like this:
function auth()
{
return new ValueWithContext($someresponse, "auth");
}
function collect()
{
return new ValueWithContext($someotherrpesonse, "collect");
}
This forces you to be explicit about the context attached to the value, which has the benefit of protecting you from accidental renamings of the functions themselves.
As per my comment, using arrays in the return will give you a viable solution to this.
It will allow a way to see what has been done;
function auth()
{
return (array("auth" => $someresponse));
}
function collect()
{
return (array("collect" => $someotherrpesonse));
}
class myClass
{
function doSomething($type)
{
if (function_exists($type))
{
$result = $type();
if (isset($result['auth']))
{
// Auth Used
$auth_result = $result['auth'];
}
else if (isset($result['collect']))
{
// Collect used
$collect_result = $result['collect'];
}
}
}
}
It can also give you a way to fail by having a return array("fail" => "fail reason")
As comments say also, you can just check based on function name;
class myClass
{
function doSomething($type)
{
switch ($type)
{
case "auth" :
{
$result = auth();
break;
}
case "collect" :
{
$result = collect();
break;
}
default :
{
// Some error occurred?
}
}
}
}
Either way works and is perfectly valid!
Letting the two user defined functions auth() & collect() call a common function which makes a call to debug_backtrace() function should do the trick.
function setBackTrace(){
$backTraceData = debug_backtrace();
$traceObject = array_reduce($backTraceData, function ($str, $val2) {
if (trim($str) === "") {
return $val2['function'];
}
return $str . " -> " . $val2['function'];
});
return $traceObject;
}
function getfunctionDo1(){
return setBackTrace();
}
function getfunctionDo2(){
return setBackTrace();
}
class DoSomething {
static function callfunctionTodo($type){
return (($type === 1) ? getfunctionDo1() : getfunctionDo2());
}
}
echo DoSomething::callfunctionTodo(1);
echo "<br/>";
echo DoSomething::callfunctionTodo(2);
/*Output
setBackTrace -> getfunctionDo1 -> callfunctionTodo
setBackTrace -> getfunctionDo2 -> callfunctionTodo
*/
The above function would output the which function returned the response

codeigniter how do i pass Value after update done and redirect to Index()

how do i pass TRUE / FALSE after update done and redirect to Index() and set
condition $viewdata['show'] to append my html sucess or something
My Controller
class Description extends CI_Controller {
public function index()
{
$viewdata['content']=$this->General_model->get_page_uri();
$viewdata['show']=; //where i want to get value when update() method
//pass value so i can show sucess / error message
$this->load->view("backend/content_view",$viewdata);
}
public function update()
{
$title=$this->input->post('txttitle');
if($title != '')
{
if(!$this->update_model->update_all($title))
{
return FALSE;
}
return TRUE;
}
redirect('Admin/Description');
}
}
My Model
public function update_all($data)
{
$this->db->set('desc',$data)
->where('desc_id','1');
if(!$this->db->update('tbl_desc'))
{
return FALSE;
}
return TRUE;
}
#Ritesh d joshi thz it work but i face problem that i can't modify when update error i test to change my field name to other to test return false;
Admin/Description/update
it show me 'A Database Error Occurred' by Codeigniter
i don't want this to show i want to keep my Admin page still same just alert nomol message error that i have set not to show many info error. how could i prevent this or this can be done by Ajax request only ?
Controller index()
if($show_ses === '0')
{
$viewdata_result = $this->General_model->rk_alert_ok('Successfully Update');
$this->session->set_flashdata('show', 'false');
}elseif($show_ses === '1'){
$viewdata_result=$this->General_model->rk_alert_no('Fail Update Request');
$this->session->set_flashdata('show', '');
}
Controller update()
if(!$this->update_model->update_all($title))
{
$this->session->set_flashdata('show', '1');
//1= false
}else{
$this->session->set_flashdata('show', '0');
//0=true
}
Use the PHP header() function.
header('Location: your_URL');
Update:
In CI, you can use redirect() function, this document will help you to understand: http://www.codeigniter.com/user_guide/helpers/url_helper.html
Please try this
class Description extends CI_Controller {
public function index()
{
$viewdata['content']=$this->General_model->get_page_uri();
$show= $this->session->flashdata('show');
if($show){
// Here is code for show and message
$viewdata['show']="message";
$this->session->set_flashdata('show', 'false');
}
$this->load->view("backend/content_view",$viewdata);
}
public function update()
{
$title=$this->input->post('txttitle');
if($title != '')
{
if(!$this->update_model->update_all($title))
{
return FALSE;
}
$this->session->set_flashdata('show', 'true');
return TRUE;
}
redirect('Admin/Description');
}
}
You can use redirection in update() as:
public function update()
{
$title = $this->input->post('txttitle');
if($title != '')
{
$status = $this->update_model->update_all($title);
if($status){
redirect(base_url().'index?show=1');
}
else{
redirect(base_url().'index?show=0');
}
}
redirect('Admin/Description');
}
than you can check the status in index() as:
public function index()
{
$viewdata['content']=$this->General_model->get_page_uri();
if(isset($this->input->post('show')) && intval($this->input->post('show')) == 0){
$viewdata['show'] = 1; // if success than show 1
}
else{
$viewdata['show'] = 0; // if error than show 0
}
$this->load->view("backend/content_view",$viewdata);
}
You can use the Header function, and to detect it you can pass the parameters too in the GET Url like below.
By default set the status as FALSE. ANd you can update the status according to your conditions either to FALSE or TRUE.
public function update()
{
$status = false;
$title=$this->input->post('txttitle');
if($title != '')
{
if(!$this->update_model->update_all($title))
{
$status = FALSE;
return FALSE;
}
$this->session->set_flashdata('show', 'true');
$status = TRUE;
return TRUE;
}
header('Location: abc.php?status='.$status);
}
Hope This will work, Do let me know in case of any confusion.

Get data return php oop

getclass.php
public $set;
//dont need to care here the code is right , here is where it final result
default;
$this->actual_device = "desktop";
echo $this->issetValueNull($this->actual_device);
public function issetValueNull($mixed)
{
$this->set = $mixed;
}
getdata.php
require_once "getclass.php";
$check_detect_device = new detect_device();
if($check_detect_device->issetValueNull->set1 = "desktop"){
"<script>console.log('desktop');</script>";
}
i need to get the data from getclass.php to getdata.php and check the final result at getdata.php , some like below;
//this data return from getclass.php
if(isset($_GET['desktop'])){
"<script>console.log('desktop');</script>";
}
but i dont know how to return the data from getclass , can any one give me some advice ?
Im not sure is this what you are trying to do, but check my example:
<?php
class getClass
{
public $actualDevice;
public function __construct()
{
$this->actualDevice = "desktop";
}
public function setActualDevice($actualDevice)
{
$this->actualDevice = $actualDevice;
return $this;
}
public function getActualDevice()
{
return $this->actualDevice;
}
public function issetActualDevice()
{
return isset($this->actualDevice);
}
}
class getData
{
public $getClass;
public function __construct(getClass $getClass)
{
$this->getClass = $getClass;
}
public function checkDetectDevice($device)
{
if ($this->getClass->getActualDevice() == $device) {
return true;
}
return false;
}
}
$getClass = new getClass();
$getData = new getData($getClass);
if ($getData->checkDetectDevice($_GET['desktop'])) {
echo "<script>console.log('desktop');</script>";
}

Codeigniter comparison input with database?

I try to comparise string from input to string in database.
This is my code:
Controller:
public function __construct() {
parent::__construct();
$this->captcha_rejestracja = rand(1,40);
}
public function register() {
$str = $this->input->post('captcharejestr');
$this->form_validation->set_rules('captcharejestr', 'kod z obrazka', 'trim|required|alpha_numeric|xss_clean|callback_captcha_check[$str]');
}
public function captcha_check($str) {
$jakacaptcha = $this->captcha_rejestracja;
$this->load->model('Tresci');
if ($str != $this->Tresci->captcha($jakacaptcha))
{
$this->form_validation->set_message('captcha_check', 'Błędnie przepisany kod z obrazka.');
return FALSE;
}
else
{
return TRUE;
}
}
Model:
public function captcha($jakacaptcha) {
$query = $this->db->query('SELECT kod FROM captcha WHERE numer='.$jakacaptcha.'');
$row = $query->row_array();
return $row['kod'];
}
I dont know where is the problem because everytime i have return FALSE from my callback ??
You don't seem to be running the form validation.
public function __construct()
{
parent::__construct();
// this is somewhat confusing, why randon value ?
// the database query should have one value :-/
$this->captcha_rejestracja = rand(1,40);
$this->load->model('Tresci');
}
public function register()
{
$this->form_validation->set_rules('field', 'label', 'callback_captcha_check' );
if(!$this->form_validation->run()){
//show the form again
return;
}
//create a new user
}
public function captcha_check($str)
{
$this->form_validation->set_message('captcha_check', 'Message here...');
$result = $this->tresci->captcha($this->captcha_rejestracja);
return ( $str == (string)$result ) ? true : false;
}

Categories