I create one quiz app. In which students attend the question and click on the next button next question appears. now the issue is that the student is on the second question and the URL like "takeQuizStudent/149?page=2" and he manually changes URL to "takeQuizStudent/149?page=1". so it should not happen. Once clicks on the next question he can't go back to the previous question.
You should check request page number from session in your controller,for example
public function show(Request $request, $id)
{
$value = $request->session()->get('pageNumber'); //2
//$id = 1
if($id < $value){
return response("invalid request",504);
}
//else update pageNumber value and do continue
// Via a request instance...
$request->session()->put('pageNumber', '3');
// Via the global helper...
session(['pageNumber' => '3']);
.....
}
Determining If An Item Exists In The Session
To determine if an item is present in the session, you may use the has method. The has method returns true if the item is present and is not null:
if ($request->session()->has('pageNumber')) {
//
}
To determine if an item is present in the session, even if its value is null, you may use the exists method. The exists method returns true if the item is present:
if ($request->session()->exists('pageNumber')) {
//
}
Related
Currently I have a refno. column in my database with the format LP00001. Now I have a add page that inserts all data that the user inserts in the input field and all this data gets sent to a table in my database, but my refno column stays null which I want to have an auto incrementing value where the last 5 digits will be +1 everytime the user submits the form.
I do not want to have it be shown before the submit button as 2 users can be on that page at the same time which means they both will get the same id which means it has to generate it only at the time of submit. Currently this is my code:
Controller class:
if ($this->form_validation->run() == FALSE)
{
$main['page'] = 'crm/listings/add';
$this->load->view('crm/index', $main);
}else {
$maindata=array('clients_id'=>$this->session->userdata('clientsessid'),
'property_for'=>$this->security->xss_clean($this->input->post('property_for')),
'property_type'=>$this->security->xss_clean($this->input->post('property_type')));
$insertid=$this->listings_model->insert_listing($maindata);
if($insertid){
$this->session->set_flashdata('message', '<div>Successfully</div>');
redirect('listings/sales');
Model Class:
function insert_listing($maindata){
$this->db->insert("crm_listings",$maindata);
$prime=$this->db->insert_id();
return $prime;
}
So I assume I'll need to do this in my model class function insert_listing since that is called when I press submit button. Here another thing will be that the model will have to check what was the last entry in the database that has to be incremented for which I'm assuming I'll have to use echo str_replace("LP","","LP00001");
I guess you just have to prepend the initials LP to the returned autoIncremented id.
function insert_listing($maindata){
// ...
$this->db->set("refno", "LP". sprintf('%05d', $prime));
$this->db->where('id', $prime);
$this->db->update("crm_listings");
return $prime;
}
I am trying to make when non auth user click to link "Add To wishes" these link going to addtowishes method and send parameter id.
After, first I check does cookie 'wishes' exist if not, I make empty array and in that array I add 'id' after I push this array in cookie.
in else case I get cookie 'wishes' and in that array I push id.But every time when i start method, cookie::get('wishes') is null.
public function addtowishes($id)
{
if(emptyArray(Cookie::get('wishes'))) {
$wishes=Array();
array_push($wishes,$id);
$cookie = cookie('wishes', $wishes, 500);
}else {
$cookie=Cookie::get('wishes');
array_push($cookie->getValue(), $id);
$cookie = cookie('wishes', $cookie->getValue(), 500);
dd($cookie);
}
}
Cookies are set with the function setcookie()
also note that the expire parameter is a unix timestamp. therefore 500 will always be expired. Use time()+60*60*24*30 for 30 days for example
I allow the user to delete items from paginated content. After deleting the item the user requests i redirect them back. I however have noticed this is buggy because if the page contains only one item and the user deletes it they are redirected to the same page which now has no records.I have 11 items on each page and use the default Laravel pagination. How can i enforce a mechanism that redirects user to the previous page if the current page is blank after deletion of the last or only item?
You can try to do simple check in controller and redirect users manually. The code just shows the idea:
$result = Model::paginate(10);
if (count($result) === 0) {
$lastPage = $result->lastPage(); // Get last page with results.
$url = route('my-route').'?page='.$lastPage; // Manually build URL.
return redirect($url);
}
return redirect()->back();
You can check the no. of results, if its less than 1 then you can redirect to the previousPageUrl as:
if ($results->count()) {
if (! is_null($results->previousPageUrl())) {
return redirect()->to($results->previousPageUrl());
}
}
I solved it by doing a Redirect::back() on the delete function. This led to the paginator function where l did the following:
//if an item was deleted by the user and it was the only on that page the number of
//items will be zero due the page argument on the url. To solve this we need to
//redirect to the previous page. This is an internal redirect so we just get the
//current arguments and reduce the page number by 1. If the page argument is not
//available it means that we are on the first page. This way we either land on the
//first page or a previous page that has items
$input = Input::all();
if( (count($pages) == 0) && ( array_key_exists('page', $input) ) ){
if($input['page'] < 2){
//we are headed for the first page
unset($input['page']);
return redirect()->action('MyController#showItems', $input);
}
else{
//we are headed for the previous page -- recursive
$input['page'] -= 1;
return redirect()->action('MyController#showItems', $input);
}
}
To implement such a logic in the controller method, destroy(), we need to know the current page number, and the items count (before we delete this item).
Pass these two pieces of information through the DELETE link, and retrieve them using the Request input method.
In your view:
<form action="{{'/items/'.$item->id.'?current_page='.$items->currentPage().'&items_count='.$items->count()}}" method="POST">
#method('DELETE')
#csrf
<button>Delete</button>
</form>
In your controller:
public function destroy(Item $item, Request $request)
{
$item->delete();
$itemsCount = $request->input('items_count');
$currentPage = $request->input('current_page');
$url = $itemsCount > 1 ? '/items/?page='.$currentPage : '/items/?page='.($currentPage - 1);
return redirect($url);
}
If it's the last page (1), then the page number becomes 0, which will still return the correct response (empty items list).
For the routes, implement a route with the two parameters, with the controller's destroy method as the callback.
If you have a resource controller, then this route has to be before the latter's route.
web.php
Route::DELETE('/items/{item_id}?current_page={number}&items_count={count}', 'ItemController#destroy');
Route::resource('/items', 'ItemController');
Here is our current set up. We have an iOS app that makes API calls to my PHP script which handles the request and queries a database via PDO and MySQL. So in this case there is an update_items.php API that the iOS app sends parameter values to and based on whether the user is updating an item or deleting an item, the API handles it accordingly and queries the database multiple times (all in one request).
Here's my predicament. I have the update bit working, but how can I use the same update API to delete an item via POST request? A quick remedy my iOS developer came up with is that if a user swipes to delete an item, he sends the item's name as "DELETE" or something along those lines. This initiates a delete query for the database record. I don't like this because anyone could figure this out and exploit the system. For example, while editing an item all I have to do is enter in DELETE for the item's name and the API would process it the same as a delete request. There has to be a better way and I would appreciate any suggestions. Below is my current PHP code that handles the API call. My suggestion, however, was to simultaneously send two API calls after a user clicks DONE for editing their item page. One to update.php if the user updates an item and another delete.php if a user decides to delete an item.
// now check for updating/deleting ingredients for the menu item
if( isset($the_request['id']) ) {
/*
iterate through avalialable values because there could be multiple ingredient ids involved. handle it.
*/
for( $i=0;$i<count($the_request['id']);$i++ ) {
// the queries. check if ingredient is being deleted or not via passed paramater value
switch($the_request['name'][$i]) {
case 'DELETE':
// assign passed parameter for delete query
$params = array(
':id' => $the_request['id'][$i]
);
// the query
$query = 'DELETE FROM TABLE WHERE id = :id';
break;
default:
// assign passed parameters for query
$params = array(
':name' => $the_request['name'][$i],
':price' => $the_request['price'][$i]
);
// Remove the empty values
$params = array_filter($params, function($param) { return !empty($param); });
// Build an array of SET parameters
$set = array_map(function($key) {
return sprintf('%s = %s', substr($key, 1), $key);
}, array_keys($params));
// don't forget the id
$params[':id'] = $the_request['id'][$i];
// the query
$query = sprintf('UPDATE TABLE SET %s WHERE id = :id', implode(', ', $set));
}
// prepare statement
if( $ingStmt = $dbh->prepare($query) ) {
$ingStmt->execute($params);
} else {
echo json_encode(array('error' => $dbh->errorInfo().__LINE__));
}
}
$ingStmt->closeCursor();
}
The REST answer is don't use a POST request, use a separate DELETE request.
On one particular page I have a button that toggles a certain field in the db. The function is
function source_toggle_paid($event_id = null, $attendee_id = null)
{
$this->authentication->checkLogin(); // Check if the user is logged in
// Check the parameters provided are null
if ($attendee_id == null || $event_id == null)
{
// If either attendee or event ids given are null, give an error message
$data = array(
'type' => 'error',
'message' => $this->message_list->get('DOES_NOT_EXIST', 'attendee') . ' ' . $this->message_list->get('BACK_TO_SOURCE_HOME')
);
// Output the error message
$this->load->view('template/main_header');
$this->load->view('template/message', $data);
$this->load->view('template/main_footer');
}
else // Otherwise, parameters are not null
{
//Load the attendee model, and toggle the paid status of the attendee
$this->load->model('Attendee');
$this->Attendee->toggle_field('paid',$attendee_id);
//Redirect the user back to the attendees page, with the used search term
redirect('admin/source_attendees/'.$event_id);
//redirect('admin/source_attendees/'.$event_id);
}
}
When I click the button I get redirected to the 404 page and the dp is unchanged, upon further playing I've found the function is never being reached. However if I type in the url manually it works, and if I right click and open in new tab, it works too
how does the routes file look like ? i got a problem that looked similar and took care of it with the routes.php settings , you should add smth like
$route['....source_toggle_paid/(:any)'] = "....source_toggle_paid";
make shure you change .... with you're controller name and then fetch the variables with
$event_id = $this->uri->segment(3); $attendee_id = $this->uri->segment(4);
make shure you change you're uri segment with the correct ones