Home > Net >  How to redirect to my new post when I created a new post | Laravel
How to redirect to my new post when I created a new post | Laravel

Time:09-28

I want to redirect to my new post when I created a new post in Laravel

But I get a ArgumentCountError

Too few arguments to function App\Http\Controllers\ArticlesController::store(), 1 passed in C:\xampp\htdocs\forum\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected

How can I fix it? Thanks

web.php

<?php

Route::resource('articles', ArticlesController::class);

Route::get('/', [ArticlesController::class, 'index'])->name('root');

Route::resource('articles.comments', CommentsController::class);

ArticlesController.php

public function store(Request $request, $id) {
    $content = $request->validate([
        'title' => 'required|max:30',
        'content' => 'required|min:10'
    ]);
    
    //限制只有透過登入才能CREATE文章
    auth()->user()->articles()->create($content);
    return redirect('articles/'. $id)->with('notice', '文章發表成功!');
}

create.blade.php

<form class="container-fluid" action="{{ route('articles.store') }}" method="post">

CodePudding user response:

Check your store() method. I think it should get only Request $request.

Example

public function store(Request $request) {
    $content = $request->validate([
        'title' => 'required|max:30',
        'content' => 'required|min:10'
    ]);
    
    //限制只有透過登入才能CREATE文章
    $article = Article::create($content); // static is not best practice, only for example

    return redirect('articles/'. $article->id)->with('notice', '文章發表成功!');
}

But before using the create method, you will need to specify either a fillable or guarded. Check docs

CodePudding user response:

Presumably you need / have a way of viewing an article anyway, whether it's just been added or not, so in your web.php you would want a GET request to retrieve an article by passing its ID:

Route::get('/article/{id}', [ArticleController::class, 'viewArticle'])-> name('article.view');

Then you would want a POST request to add a new article :

Route::post('/addarticle', [ArticleController::class, 'addArticle'])-> name('article.add');

In your ArticleController, at the end of your addArticle method, once your new article has been created, you can then return a redirect to your "view article" route referencing its name, and passing in the parameter that it expects - the new article's ID - as part of the route, like so :

$article = new Article();
... populate the article's details here ...
return redirect()->route('article.view', ['id' => $article->id]);
  • Related