skip to Main Content

I have written a member function like ::

public function details($article_seo){
        $articleDet = Articles::where(function($query) {
            $query->where('article-seo', '=', $article_seo);
            })
        ->get();
        dd($articleDet);
    }

and have used these at the beginning of laravel controller::

namespace AppHttpControllers;

use IlluminateHttpRequest;

use AppHttpRequests;
use Apparticles;  /** this is the eloquent model **/

The problem is ::
when ever i try to pass the $article_seo that I am receiving from the url data, it gives me an eror of ::: Undefined variable: article_seo

Being new to Laravel i have checked out lot of ways but unable to find one.Please help!!!!

2

Answers


  1. When you want to use an outside variable inside of a closure, you have pass the variable into the closure using the use keyword.

    public function details($article_seo){
            $articleDet = Articles::where(function($query) use ($article_seo) {
                $query->where('article-seo', '=', $article_seo);
                })
            ->get();
            dd($articleDet);
        }
    

    You can get Articles match with your article-seo easily.

        public function details($article_seo){
            $articleDet = Articles::where('article-seo', '=', $article_seo)
            ->get();
            dd($articleDet);
        }
    
    Login or Signup to reply.
  2. Closures aren’t necessary here, you can simple use the model’s where method to do what you are looking for.

    $details = Articles::where('article-seo', '=', $article_seo)->get();
    

    Cleaning that up a little bit, the where expression will use an equal sign by default, so we can omit that.

    $details = Articles::where('article-seo', $article_seo)->get();
    

    If your database values were snake cased (article_seo instead of article-seo), then you can simplify that expression even more

    $details = Articles::whereArticleSeo($article_seo)->get();
    

    That is a whole lot easier to read than the original closure based method!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search