I am trying to get variable from URL to pass to the Controller
The URL looks like this http://example.org/MyCategory or http://example.org/MyCategory-1
My DB contains table for all categories that includes category_slug column
The route is GET /#category_slug = MainController->CategorySlug
My main controller has method that supposed to handle this, which should invoke method getBySlug() from the Categories model
Main Controller
function CategorySlug($category_slug){
$categories = new Categories($this->db);
$cat = $categories->getBySlug($category_slug);
$this->f3->set('categories',$cat);
echo \Template::instance()->render('index.html');
}
Categories Model
public function getBySlug($category_slug)
{
$this->load(array('category_slug=?', $category_slug));
return $this->query;
}
As you see from the code above, I am passing variable $category_slug, but have an error
#AlexB, what error are you getting?
However, you need to pick up the variable from the URL before you pass it to your methods;
$category_slug = $this->f3->get('PARAMS.category_slug')
Related
I need a little help and I can’t find an answer. I would like to replicate a row from one data table to another. My code is:
public function getClone($id) {
$item = Post::find($id);
$clone = $item->replicate();
unset($clone['name'],$clone['price']);
$data = json_decode($clone, true);
Order::create($data);
$orders = Order::orderBy('price', 'asc')->paginate(5);
return redirect ('/orders')->with('success', 'Success');
}
and i got an error :
"Missing argument 1 for
App\Http\Controllers\OrdersController::getClone()"
.
I have two models: Post and Order. After trying to walk around and write something like this:
public function getClone(Post $id) {
...
}
I got another error
Method replicate does not exist.
Where‘s my mistake? What wrong have i done? Maybe i should use another function? Do i need any additional file or code snippet used for json_decode ?
First of all, make sure your controller gets the $id parameter - you can read more about how routing works in Laravel here: https://laravel.com/docs/5.4/routing
Route::get('getClone/{id}','YourController#getClone');
Then, call the URL that contains the ID, e.g.:
localhost:8000/getClone/5
If you want to create an Order object based on a Post object, the following code will do the trick:
public function getClone($id) {
// find post with given ID
$post = Post::findOrFail($id);
// get all Post attributes
$data = $post->attributesToArray();
// remove name and price attributes
$data = array_except($data, ['name', 'price']);
// create new Order based on Post's data
$order = Order::create($data);
return redirect ('/orders')->with('success', 'Success');
}
By writing
public function getClone(Post $id)
you are telling the script that this function needs a variable $id from class Post, so you can rewrite this code like this :
public function getClone(){
$id = new Post;
}
However, in your case this does not make any sence, because you need and integer, from which you can find the required model.
To make things correct, you should look at your routes, because the url that executes this function is not correct, for example, if you have defined a route like this :
Route::get('getClone/{id}','YourController#getClone');
then the Url you are looking for is something like this :
localhost:8000/getClone/5
So that "5" is the actual ID of the post, and if its correct, then Post::find($id) will return the post and you will be able to replicate it, if not, it will return null and you will not be able to do so.
$item = Post::find($id);
if(!$item){
abort(404)
}
Using this will make a 404 page not found error, meaning that the ID is incorrect.
I am currently trying to make a function that calls different scopeQueries such as scopeByLocation() or scopeByPublished() on models defined in an array. I've got the basics working through [this link][1]. However, when trying to access custom made query scopes that are defined in the corresponding model, I get the following error: "Call to undefined method Illuminate\Database\Query\Builder::ForLocation($location)->get()".
What I want to achieve is a single method which loops through every model in the array of models and retrieves & calls the right scopeQuery on the model, something like this:
$modelElements = $model::{$queryScope}();
Where for example $model = 'Modules\News\Models\Article'
And $queryScope is a defined queryScope in the model itself. E.g. scopeForLocation($location).
I've tested $queryScope = 'all' and I get a result just fine, however when I try to access a custom queryScope ($queryScope = 'ForLocation($location)->get') that exists within for example the Location model, I get the following error: "Call to undefined method Illuminate\Database\Query\Builder::ForLocation($location)->get()".
So this all happens in a foreach-loop where every model in my models-array gets called and then the corresponding queryScope gets called on the model.
Why does the $queryScope = 'all' method works on my dynamic models, but other scopes throw an error? I really hope someone could help me get into the right direction with this issue.
Thanks in advance,
J. Doe.
Okay, I've finally solved it the following way:
//array of models
public function models()
{
return [
'Modules\Website\Models\Article',
...
];
}
//function that retrieves all elements for a model
public function getAllElementsForModel($model, $param)
{
//instantiate model
$model = new $model;
//call queryScope
//'queryScope' could be any queryScope that is defined within your model(s),
//the parameters are needed for the associated queryScope
$query = call_user_func_array([$model, 'queryScope'], [$param1, $param2]);
$result = $query->get();
//do stuff with your $result
}
//retrieves all
public function all($param)
{
//loop through the array of models
foreach($this->models() as $model){
$this->getAllElementsForModel($model, $param);
//do stuff here...
}
}
Sharing is caring!
I want to pass multiple ID's to my controller.First for Categories and second for Food items as show in function show
My Controller is:
public function index()
{
$Foods=Food::all();
$Category=Categories::all();
return view('index.welcome', compact('Foods','Category'));
}
public function show($Food_id,$Category_id)
{
$food = Food::with('restaurant','categories')->findOrFail($Food_id);
$category = Categories::with('food')->findOrFail($Category_id);
return view('index.show', compact('food','category'));
}
My Routes are:
Route::get('index','DetailsController#index');
Route::get('index/{Food_id?}', 'DetailsController#show');
But it returns me error "Missing argument 2 for App\Http\Controllers\Detailscontroller::show()".Where is the problem in this?
You are calling a method which has 2 arguments, but in the route file you're only specifying one parameter.
Maybe your route should look something like this:
Route::get('index/{Food_id?}/{Category_id}', 'DetailsController#show');
Then you would be passing both variables.
Or modify your method declaration and remove the $Category_id parameter, as you are not passing it to the method, like this:
public function show($Food_id)
I am new to cakephp. I have a problem with calling the function. here is my issue.
In Contrloller file i get all the values using the following function
public function index()
{
$conditions = array(
'order' => array('Histroy.chat_sk DESC')
);
$this->set('histroys', $this->Histroy->find('all',$conditions));
}
In My model file have the following,
class Histroy extends AppModel
{
public $tablePrefix = 'plc_';
public $useTable = 'chat_history';
}
In my view file i have listed the values using foreach() function and that as follows
foreach ($histroys as $histroy):
$oper_name = $histroy['Histroy']['operator_fk'];
$operator_email = $histroy['Histroy']['email'];
endforeach
in that opertaor_fk is a field in history table. So i need get the operator name by another table as operators. So i need to call that function in the view.
Ex : In core we can do like as,
$operator_name = operator_name($fetch['operator_id']);
Function should be like this:
function operator_name($id)
{
// Select the value for the matched field in the operator
return $operator_name;
}
In cakephp how can i retrieve the values.
Please help me out to fix this. Thanks in Advance
Follow the blog tutorial for cake. It'll explain how to create associations and relationships between tables to let you do what is is you want, but in a nutshell, you need to create a relationship between History and Operator models and work from there.
As I am required to pirnt the ratings of products in JSON format, i have made a module with controller and rating.php file in model folder. We I run the controller it shows all the data from that table, But I required only a single row. So through the url i am passing a parameter, but it wont works. I am attaching my indexcontroller.php here. suggest me upon this.
<?php
class Modulename_CustomRating_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction ()
{
$arrParams = $this->getRequest()->getParams();
var_dump($arrParams);
$collection = Mage::getModel('Modulename_CustomRating_Model_CustomRating')->getCollection();
}
print_r (json_encode($collection ->getData()));
}
}
?>
As I am passing url as:localhost/magento/customrating?vote_id=1 , it is taking the parameter to it but returns whole table's data. I know this is due to getData(); but how to make to get the required row?
You have to use setEntityPkFilter method. Check Mage_Rating_Model_Resource_Rating_Option_Vote_Collection class for other methods.
$product_id = $this->getRequest()->getParam('product_id'); // or 'vote_id'
$collection = Mage::getModel('Modulename_CustomRating_Model_CustomRating')
->getResourceCollection()
->setEntityPkFilter($product_id);
If you want only 1 column you can try some Zend stuff because you can't use addAttributeToSelect. getSelect() returns Zend like query:
$adapter = $this->getConnection(); // $this->getConnection();
$collection->getSelect()
->reset(Zend_Db_Select::COLUMNS) // remove all columns
->columns('attribute_name'); // add only needed one
$result = $adapter->fetchAll($select);
Not sure whether this would work. It's not tested, just an idea.