How to return back twice in Laravel? - php

In Laravel, there is a function return back();, which returns the user to the previous page. Is it possible to return back(); more than once within one function to return the user back twice or several times? I tried
public function ....()
{
return back();
return back();
}
but it doesn't seem to work.

No, but you could use session system to save URLs of 2-3-4 pages back. Use Session:: facade or session() helper for shorter syntax:
$links = session()->has('links') ? session('links') : [];
$currentLink = request()->path(); // Getting current URI like 'category/books/'
array_unshift($links, $currentLink); // Putting it in the beginning of links array
session(['links' => $links]); // Saving links array to the session
And to use it:
return redirect(session('links')[2]); // Will redirect 2 links back

it works for me Redirect::to($request->request->get('http_referrer'))

Related

Undefined variable X issue when trying to display value on laravel blade

I'm trying to follow a small laravel tutorial.
In my application I have a controller called, HomeController.
In my HomeController, I have the followinf index function
public function index()
{
try {
//get autheticated users selected organisation
$organisation = $this->getSelectedOrganisationByUser(Auth::user());
//set application timezone
$this->setApplicationTimezone($organisation);
$this->setSiteConnection($organisation);
$this->setGAConnection($organisation);
if ($organisation->disabled) {
Auth::logout();
return redirect(route('login'));
}
//sales today
$sum='23';
return view('dashboard.index')
->with('organisation',$organisation,'sum',$sum);
} catch (\Throwable $exception) {
\Sentry\captureException($exception);
}
}
Here I'm trying to send this $sum value to my blade and display it. But, Every time i tried to display this value on my blade I get $sum is undefined error.
I tried to echo this on my blade as follows,
{{ $sum }}
What changes should I make, in order to display that on my blade.
I tried hard, but yet to figure out a solution
You need to pass the variables as array. Try this:
return view('dashboard.index', ['organisation' => $organisation, 'sum' => $sum]);
or another way is by using compact() like this
return view('dashboard.index', compact('organisation', 'sum'));
The method with() from /Illuminate/View/View.php accepts only two parameters.
To send multiple variable, you can
//Call with() for each variable
return view('dashboard.index')
->with('organisation',$organisation)
->with('sum',$sum);
//use an array as second parameter of view
return view('dashboard.index', ['organisation' => $organisation,'sum' => $sum]);
//use compact to create the array using the variable name
return view('dashboard.index', compact('organisation', 'sum'));
//use an array as first parameter in with (using compact or not)
return view('dashboard.index')->with(compact('organisation', 'sum'));

Laravel redirect with variable

I want to use redirect with data in Laravel8. But this code is not showing data. What is the problem in syntax ?
IN CONTROLLER
$list = BE_MEDICAL_INSURANCE_FOR_FOREIGNERS::get();
redirect()->route('dashboard')->with( ['list' => $list] );
Try the following
redirect()->route('dashboard')->with('list', $list);
for more info follow https://laravel.com/docs/8.x/redirects
First be sure that list load some data with dd($list);
After use redirect helper like
$list = //...;
return redirect()->route('dashboard', ['list'=>$list]);
you can use closure function in the route in web.php and inspect if the data is bind through the route like
Route::get('/dashboard/{list}', function($list){
dd('list');
})->name('dashboard');

How to redirect paginate to current page? - Laravel 5.5

I have set up pagination and it's working correctly. But i am not able to redirect to the current page.
E.g: If i invoke update method on currencies?page=2. I will redirect to the currencies instead of currencies?page=2.
Controller - index function
public function index()
{
$currencies = Currency::paginate(5);
return view('admin.currencies.index')
->withCurrencies($currencies);
}
Controller - Edit function
public function edit($id)
{
$currency = Currency::findOrFail($id);
return view('admin.currencies.edit')
->withCurrency($currency);
}
Controller - Update function
public function update(Request $request, $id)
{
$currency = Currency::findOrFail($id);
$currency->name = $request->name;
$currency->rate = $request->rate;
$currency->save();
return redirect()->route('currencies.index')->with('message', 'Done');
}
Views
{{ $currencies->links() }}
Check out the documentation here https://laravel.com/docs/5.5/pagination#paginator-instance-methods
You can either keep track of the page number (from referral URL if update is on different page or from query param) and pass that along in your update function like this instead of redirecting to a route.
//$page = grab page number from the query param here.
return redirect('currencies?page='.$page);
or you can also modify your index controller where you pass the page number as optional param and if null default to page 1 and if present pass that in.
$results->url($page)
Good luck.
In case someone has to do redirection to current, or any page and works with named routes.
Tested: Laravel 5
Some assumptions out of the way.
route:
$this->get('/favourite/{columnSorted?}/{sortOrder?}', 'Favourites#index')->name('favourite.list');
assumed project url in browser:
columnSorted: 'title'
sortOrder: desc
http://yoursite.net/favourite/title/desc?page=3
Now, named route redirect to page 3.
As you can see in route above, columnSorted and sortOrder are dynamic (? after param in route, e.g.: {sortOrder?}).
What it means, is that route can have both, just one or none of them.
If you wish to pass them to param array in route, you can do something like this:
/*prep redirect to, where user was params*/
$routeParams = [];
$q = '?';
if ($request->columnSorted)
{
$routeParams['columnSorted'] = $request->columnSorted;
}
if ($request->sortOrder)
{
$routeParams['sortOrder'] = $request->sortOrder;
$q = '';
}
if ($request->page)
{
$routeParams[] = $q . 'page=' . $request->page;
}
return redirect()->route('favourite.list', $routeParams);
Note above that '$q' parameter.
Last (and only last) route parameter $q must not pass '?', or constructed route from named route will have double '??' looking like:
http://yoursite.net/favourite/title/desc??page=3
... and redirect will fail.
Page number you can get from request:
$request->get('page');
// or
$request->page
... and pass it to method that will do redirect.
You must add a query string parameter to the route.
return redirect()
->route('currencies.index', ['page' => $request->get('page', 1)])
->with('message', 'Done');

How to redirect to two step backwards in Laravel?

For example
In controller I have a store function
public function store(Request $request)
{
....
return redirect()->back();
}
After store function is called, it goes to the create.blade.php view because of return redirect()->back().
But I want to redirect to further one step backwards.
How can I do that ? Thank You
You can use the Session system to save the URL all pages back. Check below steps to redirect 2 or 3 backward URL redirect.
1) First, you can get the all URLs from session system variable.
$urls = array();
if(Session::has('links')){
$urls[] = Session::get('links')
}
2) Then get the current page url.
$currentUrl = $_SERVER['REQUEST_URI'];
3) Mapping with current url to other all url.
array_unshift($urls, $currentUrl);
Session::flash('urls', $urls);
4) Get all Links fetch from session system like below
$links = Session::get('urls');
5) Then You can redirect to a particular page.
return redirect($links[2]);

Copy one row from one table to another

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.

Categories