0

getting undefined variable in my view

public function confirm()
    {
        $data = Transaction::select('number','total','package')->where('user_id','=',\Auth::user_id()->id)->first();

       return view('user.package',compact('data'));

    }

// My view

 <center> 
<h3 class="card-title"><b>You are about to buy {{$data->number}} package of {{$data->package}} for {{$data->total}}</b>
</h3>
</center>
6
  • have you checked if your $data is null for some reason? Because first() returns null if it cannot find the row. Commented Oct 30, 2018 at 12:37
  • @nakov $data is not null Commented Oct 30, 2018 at 12:54
  • 1
    Can you share the full and exact error message? What does $data exactly contain? Commented Oct 30, 2018 at 13:15
  • can you show your Transaction Model and table Commented Oct 30, 2018 at 13:18
  • $data is a variable check the code above @NicoHaase Commented Oct 30, 2018 at 13:36

4 Answers 4

2

change to \Auth::user_id()->id to \Auth::user()->id

$data = Transaction::select('number','total','package')->where('user_id',\Auth::user()->id)->first();

by getting current authenticate user id two ways.

1.Auth::id();
2.Auth::user()->id

in your view check like that isset condition row is exist or not

            @isset($data)
                <center> 
                   <h3 class="card-title"><b>You are about to buy {{$data->number}} package of {{$data->package}} for {{$data->total}}</b>
                  </h3>
                </center>
             @endif
Sign up to request clarification or add additional context in comments.

2 Comments

that's not the problem though i corrected that.... still showing undefined variable data
thanks but that's not what i wan't. i just want to pass that variable to the view so i can output the data
0

Try to use ->get() instead of ->first()

1 Comment

i don't want to use a foreach loop that's why i'm using first instead of get
0

Try auth()->user()->id instead of \Auth::user_id()->id

or You can use an Eloquent relation like

$user->with('Transaction')->select('number','total','package')->first();

1 Comment

Can you explain how that solves the issue of having an undefined index notice?
0

use this

use Auth;
public function confirm()
{
    $data = Transaction::select('number','total','package')->where('user_id','=',Auth::user()->id)->first();

   return view('user.package',compact('data'));

}

1 Comment

Can you add some explanation to the code such that others can learn from it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.