How to return to another page after finishing process in Laravel? - laravel

This is a little bit hard to understand even the title I put. Sorry about that I just do not know how to clearly explain this, but I will try...
So for example I have a controller and inside that controller I have a function which return the data in the table of my database. then in the last column of every row, I make view,add,edit,delete options as links. When a user clicks on the add for example, they will redirect to an add page. After they submit the form of the add page. they should be redirected to the first page that return the data from the table. but the problem is, the variables of foreach loop in the first page do not got recognized by laravel anymore. because they do not got processed since the route does not goes to the controller and to the function that return the data instead it goes to add function.
So I want to know is there anyway to solve this? If you could provide sample code, I would appreciate a lot thanks

From your explanation, I believe the code to go back to the original page after adding, editing etc is simply return redirect()->back(). This will take the user back to the previous page. As for data continuity, one approach would be considering using sessions. They save data globally and can be accessed from any controller once saved. To do this, simply save the data with session(['session_name' => $data]) and to retrieve the data use session('session_name'). Let me know if this helps!

If you want ti redirect after something like a login or an activation process you can do it with something like this:
return redirect()->to('login')
You can specify the path from your web.php file as you can see in my example in 'myPath'
As #DerickMasai correctly pointed out it is better to use named routes instead of hard coding the path itself.
Naming a route can work like so:
Route::get('/login', [LoginController::class, 'index'])->name('login');

Related

Link change SESSION var

I have a listing page for an e-commerce website with various items (item_list.php). This page is generated with a PHP loop and displays each item inside a <li> element. Every item is a link to the same page, called item_details.php .
When clicking on the link i want to run a script that changes a SESSION var to a certain $id (which will be excracted from the <li> itself with .innerHTML function) and then allowing the browser to move into the next page (item_details).
This is needed so i can display the proper information about each item.
I think this is possible with Ajax but I would prefer a solution that uses JS and PHP only.
(P.S.This is for a University project and im still a PHP newbie, i tried searching for an answer for a good while but couldn't find a solution)
No JS or other client-side code can set session values, so you need either an ajax call to php, or some workaround. This is not a complete answer, but something to get you thinking and hopefully going on the project again.
The obvious answer is just include it in the link and then get it in PHP from the $_GET -array, and filter it properly.
item title
If, however, there is some reason this is not a question with an obvious answer:
1.) Closest what you're after can be achieved with a callback and an ajax call. The idea is to have the actual link with a click function, returning false so the link doesn't fire at once, which also calls an ajax post request which finally will use document.location to redirect your browser.
I strongly advice against this, as this will prevent ctrl-clicks causing a flawed user experience.
Check out some code an examples here, which you could modify. You will also need an ajax.php file which will actually set the session value. https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#product-click
2.) Now, a perhaps slightly better approach, if you truly need to do this client-side could be to use an click handler which instead of performing an ajax call or setting session directly, would be to use jQuery to set a cookie and then access this data on the item_list.php -page.
See more information and instructions here: https://www.electrictoolbox.com/jquery-cookies/
<script>
$('product_li a).click(function(){
$.cookie("li_click_data", $(this).parent().innerhtml());
return true;
});
</script>
......
<li class="product_li">your product title</li>
And in your target php file you check for the cookie. Remember, that this cookie can be set to anything, so never ever trust user data. Test and filter it in order to make sure your code is not compromised. I don't know what you want to do with this data.
$_COOKIE['li_click_data'];
3.) Finally, as the best approach, you should look at your current code, and see if there is something you can re-engineer. Here's a quick example.
You could do the following in php to save an array of the values in the session on each page load, and then get that value provided you have some kind of id or other usable identifier for your items:
// for list_items.php
foreach($item as $i) {
// Do what you normally do, but also set an array in the session.
// Presuming you have an id or some other means (here as item_id), to identify
// an item, then you can also access this array on the item_details -page.
$_SESSION['mystic_item_data_array'][$i['item_id]] = $i['thedata'];
}
// For item_details.php
$item_id = // whatever means you use to identify items, get that id.
$data_you_need = $_SESSION['mystic_item_data_array'][$item_id];
Finally.
All above ways are usable for small data like previous page, filters, keys and similar.
Basically, 1 and 2 (client-side) should only be used, if the data is actually generated client-side. If you have it in PHP already, then process it in php as well.
If your intention is to store actual html, then just regenerate that again on the other page and use one of the above ways to store the small data in case you need that.
I hope this gets you going and at least thinking of how to solve your project. Good luck!

How to pass route values to controllers in Laravel 4?

I am struggling to understand something that I am sure one of you will be able to easily explain. I am somewhat new to MVC so please bear with me.
I have created a controller that handles all of the work involved with connecting to the Twitter API and processing the returned JSON into HTML.
Route::get('/about', 'TwitterController#getTweets');
I then use:
return View::make('templates.about', array('twitter_html' => $twitter_html ))
Within my controller to pass the generated HTML to my view and everything works well.
My issue is that I have multiple pages that I use to display a different Twitter user's tweets on each page. What I would like to do is pass my controller an array of values (twitter handles) which it would then use in the API call. What I do not want to have to do is have a different Controller for each user group. If I set $twitter_user_ids within my Controller I can use that array to pull the tweets, but I want to set the array and pass it into the Controller somehow. I would think there would be something like
Route::get('/about', 'TwitterController#getTweets('twitter_id')');
But that last doesn't work.
I believe that my issue is related to variable scope somehow, but I could be way off.
Am I going down the wrong track here? How do I pass my Controllers different sets of data to produce different results?
EDIT - More Info
Markus suggested using Route Parameters, but I'm not sure that will work with what I am going for. Here is my specific use case.
I have an about page that will pull my tweets from Twitters API and display them on the page.
I also have a "Tweets" page that will pull the most recent tweets from several developers accounts and display them.
In both cases I have $twitter_user_ids = array() with different values in the array.
The controller that I have built takes that array of usernames and accesses the API and generates HTML which is passed to my view.
Because I am working with an array (the second of which is a large array), I don't think that Route Parameters will work.
Thanks again for the help. I couldn't do it without you all!
First of all, here's a quick tip:
Instead of
return View::make('templates.about', array('twitter_html' => $twitter_html ))
...use
return View::make('templates.about', compact('twitter_html'))
This creates the $twitter_html automatically for you. Check it out in the PHP Manual.
 
Now to your problem:
You did the route part wrong. Try:
Route::get('/about/{twitter_id}', 'TwitterController#getTweets');
This passes the twitter_id param to your getTweets function.
Check out the Laravel Docs: http://laravel.com/docs/routing#route-parameters

CodeIgniter Pagination is not working with routing

I want to show all users page wise initially. So if I browse http://mydomain/user it will redirect to http://mydomain/user/page/1 and so on. But if I browse http://mydomain/user/1 it will show only single user with id of user.
http://mydomain/user/1 >> it works fine. But as I want pagination so I want to redirect http://mydomain/user to http://mydomain/user/page/1 always
My Routing Info is:
$route['user/(:num)'] = 'user/index/$1';
$route['user'] = 'user/page/$1';
But when I pressed to http://mydomain/user it does not rout to user/page/$1. I have index() method which output to single user information if I give slug. so get a page wise list I used routing and page method. But it is not working. it gives 404 Page not found
Could anybody have solution please..
I think you need to look at the manual for routing:
http://ellislab.com/codeigniter/user-guide/general/routing.html
As far as i can see your second route doesn´t make much sense, you are calling the method page() of your User class - and trying to pass in $1 which does not exist. I think you need to explain better what you want to achieve with your second route - I don´t really see why you need it at all at the moment.

Form from another model in a view

So I'm trying to extend the Blog tutorial adding some comments:
Post hasMany Comments
I want to display the add comment form in the same view as the 'post view'. Thing is I don't know the best way to get this approach. I thought about three ways:
Creating a function in Comments Controller to handle the data.
Creating a function in Post Controller to handle the data.
Deal with the data in the same function that deals with the post views.
The main problem with the two first 'solutions' is that the validation errors doesn't show up in the form unless I do some messy hacking of saving the invalidated field in a session variable and then parsing the variable on the beforeFilter callback, like this:
function beforeFilter () {
if ($this->Session->check('comment_error')) {
$this->Post->Comment->validationErrors = $this->Session->read('comment_error');
$this->Session->delete('comment_error');
}
}
What I basically do is adapt the invalidated fields to the actual view and allow it to show properly. This works really well, but it seems so ugly to me. What would be the best approach?
Another related question: should a controller reflect a view? I mean on that example, I thought about only having a Comment Model and dealing with all the data in the controller where's the form to add a comment (even though it's in the Post Controller).
Sounds like you're looking for the Mutlivalidatable behaviour: http://bakery.cakephp.org/articles/dardosordi/2008/07/29/multivalidatablebehavior-using-many-validation-rulesets-per-model
This allows you to define more than 1 validation ruleset per model. Use your controller to determine which one to apply upon posting something.
P.S. I have only ever used this on a Cake 1.3 project, not sure if it'll work on 2.0.
I see it this way:
Under every post there is an input box "Add comment" with a button to submit.
After submitting some text a form redirects to comments_controller where the comment is saved with this post_id, body, author, date etc.
After the comment is saved and all the logic is done it takes you back to the post.
Under each post there are all related comments displayed (having the same post_id sorted by date or whatever).

Redirect CI problem

I'm kind of new with CodeIgniter and I'm still learning (a lot).
So I have a view and when I submit a form I 'call' the controller by surfing to the right URL dynamically e.g. site/delete
class Site extends Controller {
function index(){$this->load->view('...')}
function delete() {
$this->site_model->delete_row();
$this->index();
}
}
Now when that action is done (deleted the row) I'm calling $this->index(); to redirect to my initial page (which is good) but my url stays: site/delete . I want my URL to be ../site/index (or without the /index)
Any help would be appreciated :-) .
So far I found something to solve this:
instead of:
$this->index();
I'm using:
redirect('site');
Does anyone know this is a good practice?
Redirect is what you should use.
In the user guide:
http://codeigniter.com/user_guide/helpers/url_helper.html
they use it after checking if a user is logged in. Depending on if they are or not, they redirect to a different place.
Also, note that any code after the redirect won't run. Make sure and redirect after you've done everything you need to.
My preferred method is to have actions like that handled by the same method that will be seen by the user afterwards.
What if you go to /site/delete afterwards, as a user? It will either have to detect and throw a error (show a message) or redirect to an appropriate page. /site/delete has no meaning.
For example, if a user would normally see an overview after deleting, then my form will be posted to /site/index; with index quickly checking for the condition and calling _delete() in the same controller, before doing its normal work.
That way, if the user refreshes the page, or presses 'back', things should look consistent to them.
Another example would be that /settings/edit would post to itself - this means that it can act on the post and show any output (e.g. validation errors). It means there's no /settings/do_edit location on my site, and also means that the user can go back to /settings/edit safely, and see a form for editing their settings.
I suppose this is a subjective take on a perhaps objective question, and I would encourage feedback on my view, but it's my way of avoiding the problem you have asked about.
$this->index();
Call of function in a function simply execute the functionality within that function.
And url never changed.
for changing the url you should use.
redirect ( base_url().'site');
but you should load url helper in constructor.

Resources