未定义的变量:将参数从控制器传递到视图时发布

时间:2019-04-08 19:50:09

标签: laravel

我正在尝试在Laravel中创建一个搜索功能,当我在视图中执行foreach时,它会以“未定义的变量:帖子”返回我。

我的代码:

发布模型

class Post extends Model { 

    protected $fillable = [ 
        'creator', 
        'post_url', 
        'books', 
        'likes', 
        'created_at' 
        ]; 

    public function user() { return $this->belongsTo(User::class); } 

}

首页视图:

<form action="{{ url('/search') }}" method="get">
   <input type="text" class="search-text form-control form-control-lg" name="q" placeholder="Search" required>
 </form>

控制器:

public function search($keyword)
    {
        $result = Post::where('books', 'LIKE', "'%' . $keyword . '%'")->get();
        return view('/search', ['posts' => $result]);
    }

路线:

Route::get('/search/{keyword}', 'SearchController@search');

搜索视图:

@foreach($posts as $post)
  <div class="post">{{ $post->id }}</div>
@endforeach

我在这里做什么错了?

3 个答案:

答案 0 :(得分:1)

这可能会帮助您。

Homeview.blade.php

<form action="/search" method="POST">
    @csrf // include your csrf token 

    <input type="text" class="search-text form-control form-control-lg" id="q" name="q" placeholder="Search" required>
</form>

Searchview.blade.php

<!-- or did you return a collection? --> 
@if( $posts->count() > 1 )

    <!-- then loop through the posts --> 
    @foreach( $posts as $post )
        <div class="post"> {{ $post->id }} </div>
    @endforeach

@else

    @if( !empty($posts) )
        <div class="post"> {{ $post->id }} </div>
    @endif 

@endif 

Routes / web.php

Route::post('/search', 'PostsController@show')->name('posts.show');

PostsController

use App\Post;

public function show( Request $request )
{

    $result = Post::where("books", "LIKE", "%{$request->input('q')}%")->get();

    // Uncomment the following line to see if you are returning any data
    // dd($result);

    // Did you return any results?
    return view('searchview', ['posts' => $result]);

}

答案 1 :(得分:0)

不起作用的原因,

Route::get('/search/{keyword}', 'SearchController@search');

在路由文件中,您正在寻找一个{keyword},该表单从未传递过。您的表单操作为action="{{ url('/search') }}"。路径不会获取get变量,无论如何,如果您将其称为输入“ q”。

因此,在您的控制器中,您正在寻找被传递而从未传递的关键字。

public function search($keyword)

正确的做法是像这样传递Request对象

public function search(Request $request)

然后使用$request->input('q')来检索通过表单传递的值。

在您的示例中,$keyword始终为空白。

更正的代码

主页视图:

<form action="{{ url('/search') }}" method="get">
   <input type="text" class="search-text form-control form-control-lg" name="q" placeholder="Search" required>
 </form>

控制器:

public function search(Request $request)
{
    $result = Post::where('books', 'LIKE', "%{$request->input('q')}%")->get();
    return view('/search', ['posts' => $result]);
}

路线:

Route::get('/search', 'SearchController@search');

Searchview:

@foreach($posts as $post)
  <div class="post">{{ $post->id }}</div>
@endforeach

答案 2 :(得分:-1)

尝试:

return view('/search')->with('posts', $result);

甚至是动态变种。

return view('/search')->withPosts($result);