Abdallah Sakre
Abdallah Sakre

Reputation: 99

Laravel Undefined variable when passing variable

Beginner question :

I'm passing the $wordsRow variable from the WordsController to the results2 blade. $wordsRow contains a row in the words table.

WordsController code :

$wordsRow = Words::where(DB::raw('body'),'LIKE', "%{$body}%")->get();

        return view('results2', [
    'message' => $message ,
    'wordsRow' => $wordsRow]);

And then in results2 blade, passing the body and id columns of wordsRow to the dashboard2 blade.

@if (isset($wordsRow))
     @foreach ($wordsRow as $wordsRow)
<a href="{{route('dashboard2',[
     'wordsRowB'=>$wordsRow->body,
    'wordsRowId'=>$wordsRow->id])}}">{{$wordsRow->body}}</a> <br>
     @endforeach
@endif

And then in dashboard2 blade, I have a problem as follows :

If I use a form with an empty action <form action="#" method="post"> , no issues occur, and the dashboard view opens with no problems. While if I use :

<form action="{{route('post.create',['wordID' => $wordsRowId])}}" method="post">

I receive the following error :

ErrorException in aadedc1cbff958325ddae8e9ce9778562c4daf4a.php line 83: Undefined variable: wordsRowId (View: D:\wamp\www\Xxxxx\resources\views\dashboard2.blade.php)

Any help ?

Upvotes: 1

Views: 759

Answers (1)

Abdallah Sakre
Abdallah Sakre

Reputation: 99

The problem was in the route as Gerard reches mentioned.

I modified the dashboard2 route to hold the 2 variables, and modified the controller to also recieve the 2 variables and then return them back to the Dashboard2 view, as follows :

Controller code :

 public function getDashboard($wordsRowId, $wordsRowB)
    {
       $posts = Post::orderBy('created_at', 'desc')->get();
        //$posts=post::all();
        //return view('dashboard');
        return view('dashboard2', [
            'posts' => $posts,
            'wordsRowB'=> $wordsRowB ,
            'wordsRowId'=> $wordsRowId
            ]);

    }

Route code :

Route::get('/dashboard2/{wordsRowB}/{wordsRowId}', [
    'uses' => 'DashController@getDashboard',
    'as' => 'dashboard2',
    'middleware' => 'auth'
]);

Upvotes: 0

Related Questions