3.1Laravel控制器(Controller)之基础(Basic)

//只生成控制器类,类体为空
php artisan make:controller ArticleController
//同时生成控制器类和实例方法,但方法体为空
php artisan make:controller ArticleController --resource
//同时生成控制器类和实例方法并同时生成模型类,但方法体和模型类体为空
php artisan make:controller ArticleController --resource --model=Article
class UserController extends Controller
{
    //
}

index

public function index()
    {
        $articles = Article::all();
        return view('articles.index', ['articles' => $articles]);
    }

create

public function create()
    {
        return view('post.create');
    }

store

public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required',
            'body' => 'required|min:10',
        ]);

        $article = new Article;
        $article->title = $request->title;
        $article->body = $request->body;
        $article->save();
        return redirect('/')->with('success', '文章创建成功'); 
    }

show

public function show(Article $article)
    {
        return view('articles.show', ['article' => $article]);
    }

edit

public function edit(Article $article)
    {
        return view('articles.edit', ['article' => $article]);
    }

update

public function update(Request $request, Article $article)
    {
        $validated = $request->validate([
            'title' => 'required',
            'body' => 'required|min:10',
        ]);

        $article->title = $request->title;
        $article->body = $request->body;
        $article->save();
        return redirect('/')->with('success','更新文章成功!');
    }

destroy

public function destroy(Article $article)
    {
        $article->delete();
        return redirect('/')->with('success','删除文章成功!');
    }

原创文章,作者:huoxiaoqiang,如若转载,请注明出处:https://www.huoxiaoqiang.com/php/laravel/5573.html

发表评论

登录后才能评论