Skip to content
Advertisement

How to use isset in if return variable in laravel

i have some condition if request isset or no and retun in view blade laravel like this:

$compare1 = $request->compare1;
$compare2 = $request->compare2;

if (isset($compare1)) {
    $laptop1 = Laptop::where('slug', $compare1)->firstOrFail();
    return view('compare.index', ['laptop1' => $laptop1->id]);
  } elseif(isset($compare2)) {
    $laptop2 = Laptop::where('slug', $compare2)->firstOrFail();
    return view('compare.index', ['laptop1' => $laptop1->id, 'laptop2' => $laptop2->id]);
  }elseif(isset($compare1, $compare)) {
    $laptop1 = Laptop::where('slug', $compare1)->firstOrFail();
    $laptop2 = Laptop::where('slug', $compare2)->firstOrFail();
    return view('compare.index', ['laptop1' => $laptop1->id, 'laptop2' => $laptop2->id]);
  }else {
    return view('compare.index');
  }

if isset($compare1, $compare) run, $laptop2 not found, any solution for this case…? Thanks before

Advertisement

Answer

The structure you have is incorrect. Currently, your code elseif(isset($compare1, $compare)) will never execute because if either $compare1 or $compare2 are set, your if statement will already exit before it gets to the 3rd one. You also have a lot of redundant code (repeating a line of code depending on which if block is executed) which is easily reduced to fewer lines and cleaner code.

Simple Approach

Consider this; (You should be able to replace your entire if block with this)

//set up an empty array to return
$return = [];

//check if `$compare1` is set, and add to return array if it is
if(isset($compare1)) {
    $return['laptop1'] = (Laptop::where('slug', $compare1)->firstOrFail())->id;
}

//same as above but for `$compare2`
if(isset($compare2)) {
    $return['laptop2'] = (Laptop::where('slug', $compare2)->firstOrFail())->id;
}

return view('compare.index', $return);

Dynamic Approach

This may be a little bit overkill if you are just doing 2 comparisons but it definitely has some upsides.

  • Similar amount of code as the simple approach
  • No need to define separate variables for every comparison (e.g $compare1 = $request->compare1;, etc)
  • Easily add more comparisons to your return by simply adding them to the $comparisons array
  • Future Proof

Code:

//empty array to return
$return = [];

//list of variables to compare
$comparisons = ['compare1', 'compare2'];

//loop through each comparison
foreach($comparisons as $key => $request_object) {

    $count = $key + 1; //keys start at 0, so we add 1 to make it count sequentially 1,2,3 ...
    $comparison = $request->{$request_object}; //grab your comparison object

    //check if comparison object is set, add it to return array if it is
    if(isset($comparison)) {
        $return["laptop{$count}"] = (Laptop::where('slug', $comparison)->firstOrFail())->id;
    }
}

return view('compare.index', $return);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement