Asked  2 Years ago    Answers:  5   Viewed   539 times

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
Saturday, December 24, 2022

Actually i'm not even mad that's amazing because I found a solution to my problem... just around 5 min after I post my question... And I spend around 2 hours to find a solution...

All I did was:

php artisan clear-compiled
php artisan ide-helper:generate
php artisan optimize

and reload the blade.php.

I have no idea why, but it works now. It seems I forgot to run the above commands after I got Laravel Collective 5.2 in the project. This could be the reason that form command didn't work. .___.;;

I hope someone could use this information for their own project.

Friday, December 16, 2022

As far as I can see and understand you're telling your unit test that when you call $request->has() on your request object that it should return the $requestParams array, not true or false, or anything else.

Unless you specifically check what is send with a method call your mock doesn't actually care what is send, it just cares that it was called.

You might want to explore creating an empty request and filling it with data if that is possible in your use case as that'll let you run your unit test with more ease and less issues. This won't work in all cases.

You could include what assertions you're making in your unit test so we can see more clearly what you're running into, but as it is. It returns exactly what you're telling it to return. Even if that's not what you actually want it to return.

Mocks are used to separate your Unit-Test from the rest of your system. As such you usually tend to only check if a specific method is called to see if your code actually exits to the class you mocked and if it has the expected data you'd send along. In some extreme cases you can want to mock the system you're actually testing, but this usually indicates that your code is too dependent on other classes or it's doing too much.

Another reason to use mocks is to satisfy Type Casting constraints in your method calls. In these cases you'll usually create an empty mocked object and fill it with some dummy data your code will accept or break on to test the code.

In your case it seems you want to check if your code actually works correctly and for this I'd suggest either not mocking the request, or making specific tests where you tell it to return true, or false (test for both cases)

So something along the lines of:

    ->willReturn(true); // or false in your next test

Edit: As you mentioned in the comment Below you ran into the issue that you're using the has method multiple times in your code and ran into issues.

The Questions I've linked to in my response comment go into greater detail but to sum it up, you can use an inline function or the at() method to deal with multiple cases.

With at() you can supply specific iterations of the code to hit only that bit of the test. It has been mentioned that this makes your tests rather brittle as any has added before the previous ones would break the test.



The inline function (callback) solution would allow you to customize your test to allow multiple cases and to return data as required. Unfortunately I'm not too familiar with this concept as I haven't used it myself before. I suggest reading the PHPUnit docs for more information about this.

In the end I'd still suggest not mocking the request and instead making an empty request that you'll fill with the data you want to check. Laravel comes with some impressive methods that'll let you manually fill the request with a lot of data you'd usually test against.

For example you can add data (post/get data) by using

request->add(['fieldname' => 'value'])

As a last few pointers I'd like to mention that it seems you use var_dump. Laravel comes with two of it's own functions that are similar and quite useful in debugging. You can use dd(); or dump(); dd(); dumps and stops the execution of code, while dump(); just outputs whatever you decide. so you could do dd($request); or dump($request); and see what the variables/class objects/etc holds. It'll even put it in a rather spiffy layout with some Javascript and such to allow you to see what's in it and such. Might want to check it out if you didn't knew it existed.

Sunday, November 6, 2022

You can achieve what you want in one iteration over the data using reduce like so:

$variations = [];

$result = array_reduce($filters, function ($result, $filter) use ($variations) {
    $filter['brand']['name'] = strtolower($filter['brand']['name']);
    if ($result['brands']->where('name', $filter['brand']['name'])->isEmpty()) {

    foreach ($filter['options'] as $option) {
        $option['name'] = strtolower($option['name']);

        if ($result['options']->where('name', $option['name'])->isEmpty()) {

    if (isset($filter['rating']['id'])) {
        if ($result['ratings']->where('id', $filter['rating']['id'])->isEmpty()) {

    foreach ($filter['tags'] as $tag) {
        $tag['name'] = strtolower($tag['name']);

        if ($result['tags']->where('name', $tag['name'])->isEmpty()) {

    foreach ($filter['variations'] as $variation) {
        $variation['name'] = strtolower($variation['name']);
        $variationName = $variation['name'];         
        $children = collect($variation['children'])->pluck('name');

        if ($result['variations']->where('name', $variation['name'])->isEmpty()) {
            $variations[$variationName] = $children;

        } else {
            $different = $variations[$variationName]->diff($children);
            if ($different->isNotEmpty()) {
               foreach ($different as $childName) {

    return $result;

}, collect([
    'brands' => collect(),
    'options' => collect(),
    'ratings' => collect(),
    'tags' => collect(),
    'variations' => collect()

If you need the result as an array, you can use the collection's toArray method:

Friday, August 12, 2022

I think your best solution is using Transformer. Using your current implementation what I would recommend is fetching only the needed field in your loop, i.e:

foreach ($recipes as $recipe) {
    $recipe = $recipe->ingredients->only(['ingredient_name', 'ingredient_amount']);

While the above might work, yet there is an issue with your current implementation because there will be tons of iteration/loop polling the database, I would recommend eager loading the relation instead. But for the sake of this question, you only need Transformer.

Install transformer using composer composer require league/fractal Then you can create a directory called Transformers under the app directory.

Then create a class called RecipesTransformer, and initialize with:

namespace AppTransformers;

use AppRecipe;

use LeagueFractalTransformerAbstract;

class RecipesTransformer extends TransformerAbstract
    public function transform(Recipe $recipe)
        return [
            'name' => $recipe->name,
            'description' => $recipe->description,
            'ingredients' => 
                $recipe->ingredients->get(['ingredient_name', 'ingredient_amount'])->toArray()

Then you can use this transformer in your controller method like this:

use AppTransformersRecipesTransformer;
public function getRecipe()
     return $this->collection(Recipe::all(), new RecipesTransformer);
     //or if you need to get one
     return $this->item(Recipe::first(), new RecipesTransformer);

You can refer to a good tutorial like this for more inspiration, or simply go to Fractal's page for details.


In order to get Fractal collection working since the example I gave would work if you have Dingo API in your project, you can manually create it this way:

public function getRecipe()
    $fractal = app()->make('LeagueFractalManager');
    $resource = new LeagueFractalResourceCollection(Recipe::all(), new RecipesTransformer);

     return response()->json(

In case you want to make an Item instead of collection, then you can have new LeagueFractalResourceItem instead. I would recommend you either have Dingo API installed or you can follow this simple tutorial in order to have in more handled neatly without unnecessary repeatition

Tuesday, December 27, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :

Browse Other Code Languages