YaSh Chaudhary YaSh Chaudhary - 1 year ago 75
PHP Question

Undefined variable in laravel 5.2 don't know why

I want to display the content saved on the database on my view page. I've applied relationship between user and account.

I've another relationship between user and post which is working perfectly.

The error i am getting is:

ErrorException in 0401a2c6f4dbf412d9f16ba1e4ced9e54c8bb622.php line 132:
Undefined variable: accounts (View: E:\wamp\www\gal\resources\views\myplace.blade.php)

my view code: http://laravel.io/bin/l5bJJ

my controller: http://laravel.io/bin/W40lE

Answer Source

Given this code...


namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
use App\Account;
use Illuminate\Support\Facades\Auth;

class AccountController extends Controller
    public function account(Request $request)
        $account = new Account();
        $account->estado = $request['textfield4'];

        return redirect()->route('myplace');

    public function getaccount()

        $accounts = Account::orderBy('created_at','desc')->get();

        return view('myplace',['accounts'=>$accounts]);

$account->estado = $request['textfield4']; should be $account->estado = $request->input('textfield4', 'some_default_value');

User::find(Auth::id())->accounts; does literally nothing as you don't save the result, and $accounts = Account::orderBy('created_at','desc')->get(); is sorting all accounts.

As for how none of your Accounts are being shown with orderBy is probably due to not having any query about what to select or conditions for it to be true. Default values may help, but if you have something funky it may be broken. There isn't much we can do without more code.

Another guess I have about this is return view('myplace',['accounts'=>$accounts]); should be return view()->make('myplace',['accounts'=>$accounts]);


His problem was he was navigating to /myplace which doesn't route to getaccount() it routes to getmyplace(), which didn't have the $accounts variable passed.