I am using this Restserver in combination with CodeIgniter.
It seems to work pretty well except when I use URL's like these;
mydomain.com/api/example/1234/
wherein 1234 is the ID I'm requesting.
Code like this doesn't seem to work:
class Example extends REST_Controller {
public function index_get() {
print($this->get("example"));
}
}
It doesn't seem to matter whether it is a GET or POST request. There must be a way I can just retrieve the ID from the URL..
The URL's segments should equal to these:
api = Controller
example = Resource
Parameters must be in key-value pairs:
id = Key
1234 = Value
It seems that your 1234 is treaded as a key, but with no value for it. Try to change your URL to the following: mydomain.com/api/example/id/1234/, which would translate to: mydomain.com/controller/resource/key/value/
There is also a very detailed tutorial here: http://net.tutsplus.com/tutorials/php/working-with-restful-services-in-codeigniter-2/
EDIT:
Since your controller is in a sub-folder, your URL's segments should be constructed like this:
api/example = Controller
user = Resource // basically the method name + the http method e.g. user_get(), or user_post(). I just made 'user' up, for your app can be whatever it is that people will access via your api
Parameters must be provided as key-value pairs:
id = Key
1234 = Value
So then your URL would look like this: mydomain.com/api/example/user/id/1234/
in the case of a GET REQUEST you just define the parameters in the header of the function like this:
public function index_get($param) {
print($param);
}
if you want to make it optional then:
public function index_get($param="") {
if ($param=="") {
print("No Parameters!");
} else {
print($param);
}
}
If I want to send "POST" parameters, I just create a POST METHOD and receive them as such...
public function index_post() {
$params = $this->post();
if (isset($param['id'])) {
print($param['id']);
} else {
print("No Parameters!");
}
}
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 creating a REST server and would like to create a url like so
DELETE /companies/3/employees/45
The endpoint should delete employee 45, which belongs to company 3.
How exactly would i go about creating a above URL using codeigniter.
Try the following:
In your routes.php add a new route:
$route['companies/(:num)/employees/(:num)'] = 'companies/employees/$1/$2';
Where companies is the controller and employees is the action.
and in your controller, write action something like:
//Use some kind of input validations for the Ids
public function employees($companyId = 0, $employeeId = 0)
{
if(strtolower($_SERVER['REQUEST_METHOD']) == 'delete')
{
//delete query here
}
}
This uses CI routing to get params, and uses superglobal $_SERVER to determine whether the Request Method being used for the call is DELETE.
first you need to make a rest app like this link
Then you can make a route like
$route["companies"]["delete"] = 'company/delete';
In your controller company
function delete ( ) {
foreach($this->input->post() as $item => $value){
${$item} = $value;//making variables $employee_id, $company_id
}
//logic to delete
}
You need to send that info by post or make almost the same sending it to get
I have the following route in my routes.web.php. Looks like this...
Route::get('/spielerAuswahl/{somevar}', 'SpielplanController#getHeimGast');
In the variable {somevar} I have for example Nr1=111&Nr2=222. The route works fine in a get to SpielplanController...
public function getHeimGast(){
$var = $somevar;
return view('test')->with('variableControllerSomevar', $var);
}
In this function I want to put the Nr1=111&Nr2=222 in the $var and make then an easy output of this variable in the view. How to get that?
Though the answer come late, but you can put Nr1=111&Nr2=222 as uri with proper encoding. For javascript, encodeURIComponent can be used to escape certain characters to form a valid URI:
encodeURIComponent('Nr1=111&Nr2=222');
// output: Nr1%3D111%26Nr2%3D222
To request server, using this url:
http://example.com/spielerAuswahl/Nr1%3D111%26Nr2%3D222
The controller function then receives correct form of variable as follows:
public function getHeimGast ($somevar) {
$somevar // = Nr1=111&Nr2=222
}
Only URI segments can be map as route variables in Laravel, no query string variables.
You can simply fetch those like these:
public function getHeimGast(){
$vars = request()->all();
return view('test', $vars);
}
In your test blade, you can use those query vars, eg( Nr1=111&Nr2=222 ) as:
$Nr1, $Nr2 ... and so on...
NOTE: given a query like this: /spielerAuswahl?Nr1=111&Nr2=222
I have been banging my head against this problem for about an hour now. I have looked high and low but nothing is working for me. This should be simple and I am sure it is.
I am trying to pass some parameters in CodeIgniter to a URL and nothing seems to be working. Here is my controller:
class Form_controller extends CI_Controller {
public function change($key = NULL) {
if (is_null($key)) {
redirect("reset");
} else {
echo "Hello world!";
}
}
}
Here is my route:
$route['change/(:any)'] = "form_controller/change/$1";
Every time I visit /index.php/change/hello I get the string "Hello world!" but when I visit /index.php/change I got a 404 not found.
What I am trying to do is pass a parameter to my controller for the purposes of checking the DB for a specific key and then acting upon it. If the key does not exist in the DB then I need to redirect them somewhere else.
Any thoughts on this?
Never mind, I figured it out. I ended up making two different routes to handle them, like so:
$route['change'] = "form_controller/change";
$route['change/(:any)'] = "form_controller/change/$1";
And the function in the controller looks like this now:
public function change($key = NULL) {
if (is_null($key)) {
redirect("reset");
} else if ($this->form_model->checkKey($key)) {
$this->load->view("templates/gateway_header");
$this->load->view("forms/change");
$this->load->view("templates/gateway_footer");
} else {
redirect("reset");
}
}
If anyone has a better solution, I am all ears. This worked for me though.
This might help you out
public function change() {
$key = $this->uri->segment(3);
http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html
This allows you to grab the segment easily using the CI url helper
index.php/change/(3RD Segment) this part will go into that variable $key.
This may not be what you are looking for but it is very useful if you are trying to pass two variables or more because you can just grab the segment from the url and store it into the variable
I have this format on links:
blah/link/11
where blah is the controller and link is a function inside it. But now I want to send a number in the querystring. In normal non-MVC way I would have done like this:
page.php?id=11
So what should I do for getting the eleven in my link function?
class Blah extends Controller {
function link( $id ) {
// $id == 11
}
}
reachable via URL blah/link/11
There may be other ways to go about this, but it looks like CodeIgniter has a URI Class that will allow you to retrieve specific segments of your URI. So something like
$id = $this->uri->segment(3); //from a controller, I assume
should get you what you want.
It also looks like CodeIgniter will take additional URI parameters and pass them through as parameters to your action function.
#http://example.com/index.php/products/shoes/sandals/123
class Products extends Controller {
function shoes($sandals, $id)
{
echo $sandals;
echo $id;
}
}