Siriguuu
Siriguuu

Reputation: 9

Too few arguments when passing variables between blade files (laravel)

I am trying to send user variable from users.show.blade file here:

@extends('layouts.myapp')

@section('title', 'User')

@section('content')
<ul>
    <li>Name: {{$user->name}}</li>
    <li>Email: {{$user->email}}</li>
    <li>
        <a href="{{route('posts.index', ['id' => $user->id])}}">Posts</a>
    </li>
</ul>
<a href="{{route('users.index')}}">Back</a>
@endsection

To an posts.index.blade file for a post here:

@extends('layouts.myapp')

@section('title', 'Posts')

@section('content')
<a href="{{route('posts.create')}}">Create Post</a>
<ul>
    @foreach ($posts as $post)
        <p>{{$user}}</p>
        <li><a href="/posts/{{$post->id}}">{{$post->title}}</a></li>
        <li><a href="{{route('posts.show', ['id'=>$post->id])}}">{{$post->title}}</a></li>
    @endforeach
</ul>
@endsection

By calling the PostController showByUser method:

public function showByUser($id){
    $posts = Post::all();
    $user = User::FindOrFail($id);
    return view('posts.index', ['user'=>$user, 'posts'=>$posts]);
}

In route:

Route::get('/posts', [PostController::class, 'showByUser'])->name('posts.index');

I get the following error:

'Too few arguments to function App\Http\Controllers\PostController::showByUser(), 0 passed in /var/www/html/vendor/laravel/framework/src/Illuminate/Routing/Controller.php on line 54 and exactly 1 expected'

I can't figure out where am I not passing the 1 variable is asking for.

Upvotes: 0

Views: 173

Answers (1)

Bhargav Chudasama
Bhargav Chudasama

Reputation: 7165

you have missed route param in post index route like this way {id}

if have optional param than write this way {id?} else {id}

Route::get('/posts/{id}', [PostController::class, 'showByUser'])->name('posts.index');

you have used same route with id param change their name

Route::get('/get_posts/{id}', [PostController::class, 'showByUser'])->name('posts.index');
Route::get('/view_posts/{id}', [PostController::class, 'show'])->name('posts.show'); 
Route::delete('/delete_posts/{post}', [PostController::class, 'destroy'])->name('posts.destroy'); 

Upvotes: 1

Related Questions