how to pass two arrays from model file to controller file - codeigniter

I want to return two arrays in a single function in the model and post the result in view but it gives an error.
And also I want to output a certain element of an array.
public function index(){
$this->load->model("model");
$array['thisarray'] = $this->model->Hello();
$arrayy['yep'] = $this->model->Hello();
$this->load->view("viewfile",$array);
$this->load->view("viewfile",$arrayy);
}
below is my model.php file.
public function Hello()
{
return ['title' => 'My Title','heading' => 'My Heading'];
return ['a'=> "helo",'b' =>"yello", 'c' =>"mello"];
}
below is my view file
<?php
echo "<pre>";
print_r($thisarray);
print_r($yep)
echo "</pre>"
?>
it gives an error saying yep is undefined variable.

this is impossible
a possible solution would be
your model
public function Hello()
{
return
[
'yep' => ['title' => 'My Title','heading' => 'My Heading'],
'thisarray' => ['a'=> "helo",'b' =>"yello", 'c' =>"mello"]
];
}
your controller
public function index()
{
$this->load->model("model");
$this->load->view("viewfile",$this->model->Hello());
}
and your view stays the same

you need to just change just your controller like this and you are all set.
public function index()
{
$this->load->model("model");
$array['thisarray'] = $this->model->Hello();
$array['yep'] = $this->model->Hello();
$this->load->view("viewfile", $array);
}
After modifying your controller like given above, you will be able to access you array as you are accessing it in your view.

Related

Laravel model function best prickets

im new in Laravel , I have an issue as below
I make in category model query to check is category is exist or not
as below
public function scopeIsExist($query ,$id)
{
return $query->where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC')->first();
}
and my controller is
public function edit($id)
{
$dataView['category'] = Category::IsExist($id);
if(!$dataView['category'])
{
return view('layouts.error');
}else{
$dataView['title'] = 'name';
$dataView['allCategories'] = Category::Allcategories()->get();
return view('dashboard.category.edit')->with($dataView);
}
}
my problem is when I use method isEXIST if id not found it not redirect to error page but ween i remove ISEXIST AND replace it as below
$dataView['category'] = Category::where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC')->first();
it work well .
can any one help me
That's because local scope should return an instance of \Illuminate\Database\Eloquent\Builder. You should remove the first() in the scope and put it in the controller.
Redefine your scope like so:
public function scopeIsExist($query ,$id)
{
return $query->where(['deleted' => 1, 'id' => $id])->orderBy('id', 'DESC');
}
In your controller edit method:
$dataView['category'] = Category::IsExist($id)->first();
You can have a look to the doc for local scopes https://laravel.com/docs/8.x/eloquent#local-scopes

Method Illuminate\Database\Eloquent\Collection::attach does not exist error in laravel 8

I was trying to add categories to products. I want to do it with a couple table between items and categories. I made a function in my controller to send it to the database. However, when I want to send it, I get the following error, and I don't know I can fix it. Method Illuminate\Database\Eloquent\Collection::attach does not exist.
Controller:
public function store(ItemsValidatorRequest $request)
{
if ($files = $request->image) {
$destinationPath = 'images';
$profileImage = date('YmdHis') . "." . $files->getClientOriginalExtension();
$files->move($destinationPath, $profileImage);
}
else {
return redirect()->back()->with('warning', 'Mislukt');
}
$user = Auth::user()->id;
Item::create([
'user_id' => $user,
'item_title' => $request->titel,
'item_img' => $profileImage,
'item_description' => $request->beschrijving,
'item_price' => $request->prijs,
'item_slug' => $this->slugify($request->titel)
]);
$items = Item::latest()->get();
// line where it goes wrong
$items->each->categories()->attach($request->categories);
return redirect()
->route('admin.items.index')
->with('success', 'Het item is toegevoegd aan je verlanglijst');
}
My model :
public function categories()
{
return $this->belongsToMany('App\Models\Category');
}
Laravels higher order function calls, take a single method call, not multiple. Therefor if you create an helper method on the Item class, it will solve your problem.
class Item {
public function attachCategories($categories) {
$this->categories()->attach($categories);
}
}
Which will make it possible to assign categories like so.
$items->each->attachCategories($request->categories);

how can i get language value randomly in laravel controller?

class DynamicDependent extends Controller
{
function fetch(Request $request)
{
$value = "home";
$value2 = Lang::get('home.'.$value.'');
}
}
output :'home.home'.
But i need value from language file.
please guide me to get this.
It seems like you are trying to get a translation. For that you can use the trans helper method like this:
//In your resources/lang/{some_lang_code}/home.php
return [
'home' => 'My translation',
];
//In your controller
$value = "home";
$value2 = trans('home.'.$value); //My translation

How do I pass a selectbox variable to the View from the Controller in CodeIgniter?

I want to pass a variable (selectbox id, which comes from database) to the view from the controller, but do not know how to do it.
Your original question wasn't that clear, but after reading the comments you could do this.
Controller
//whatever function you're using to populate your original array below.
$data['all'] = $this->model_name->getData();
//then run that data through a foreach loop to populate the dropdown variable.
foreach($data['all'])
{
$data['idDropDown'][$data['all']['id']]=$data['all']['ad'];
}
This will pass an array like: [455]=>Aliağa, [456]=>Balçova to the view as $idDropDown along with your original data as $all
Then in the view just used CI's form dropdown.
echo form_dropdown('id',$idDropDown);
Let's say you have a controller called article and a method index then in your view you will have :
<?php
echo form_open('article/index');
echo form_input('text');
echo form_close;
?>
And in your controller something like:
public function index()
{
if($this->input->post()) {
$this_is_catched_text = $_POST['text'];
}
}
This is without validation and other stuff. Just you get the idea how it works.
In your case it will be like this
$ilce = array(array("id" => 455, "il_id" => 35,"ad" => "Aliağa"),
array("id" => 456, "il_id" => 35, "ad" => "Balçova"));
$options = array();
foreach($ilce as $x) {
$options[$x['id']] = $x['ad'];
}
echo form_dropdown('names', $options);

declaring class level variables in codeigniter

I am new to CI and what I want to do is to have a class level variable (which e.g is an array). But it seems like CI, despite all high bragging, doesn't support this feature. Nothing has been mentioned in the user guide about it. There is a heading called private functions and variables but the text has been seemingly kept silent regarding variables.
I want to have something like :
class OrderStats extends CI_Controller {
protected $arr_CoreCountry = ('0'=>'uk', '1'=>'us');
public function __construct()
{
parent::__construct();
// Your own constructor code
}
public function index()
{
$this->load->model('orders', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
$data['result'] = $this->Testmodel->get_reports();
$this->load->view('test', $data);
}
public function getOrderStats()
{
$this->load->model('Orderstatsmodel', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
foreach ($arr_CoreCountry as $key => $value)
{
$data['result'] = $this->Orderstatsmodel->get_orderStats($key);
}
// $data['result'] = $this->Orderstatsmodel->get_orderStats(0);
$this->load->view('orderstats', $data);
}
Remember, when I declare $arr_CoreCountry variable at the place as it is in this post, I constantly see a syntax error message.
When I place it some where inside any function then of course, it gets out of scope and I keep getting an error messag that $arr_CoreCountry is an undefined variable.
So the question is where do I define it?
Expect a quick response as half of my day has been wasted just because of this s*** from codeigniter.
This should work:
class OrderStats extends CI_Controller {
protected $arr_CoreCountry = array('0'=>'uk', '1'=>'us');
public function getOrderStats()
{
$this->load->model('Orderstatsmodel', '', TRUE);
//$data['result'] = $this->Testmodel->get_entries();
foreach ($this->arr_CoreCountry as $key => $value)
// etc
}
you are omitting the $this-> in your original code.
Edit
Here was my test code ~
class Testing extends CI_Controller {
protected $foo = array('test'=>'foo', 'bar'=>'baz');
function index() {
foreach($this->foo as $k => $v) {
echo $k . ' = ' . $v . '<br />';
}
}
}
// outputs:
test = foo
bar = baz
perhaps you can post your syntax errors as they appear to be missing from your original post.
You have a syntax array declaration error. Please try to declare array like this:
protected $arr_CoreCountry = array('0'=>'uk', '1'=>'us');
Please check out this site for array manual: http://php.net/manual/en/language.types.array.php
I solved the problem myself.
There are two things which I changed
protected $arr_CoreCountry = ('0'=>'uk', '1'=>'us');
was changed to
var $arr_CoreCountry = array(0=>'se', 1=>'fi',2=>'de');
and
foreach ($arr_CoreCountry as $key => $value)
was changed to
foreach ($this->arr_CoreCountry as $key => $value)
I was missing $this but when I put it there, it was still not working. When I changed protected to var, it worked.
Thanks everyone for your input...

Resources