我是laravel API的初学者,我想显示文章列表(方法索引),我已经创建了模型文章,但是我不能。
你好,我是laravel API的初学者,我想显示文章列表(方法索引),我已经创建了模型Article,但是我不能。
ArticleController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Article;
use App\Http\Resources\Article as ArticleResource;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$articles= Article::paginate(15);
return ArticleResource::collection($articles);
}
create_table_articles
public function up()
{
Schema::create('articles', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('body');
$table->timestamps();
});
}
AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Schema::defaultStringLength(191);
}
ArticlesTableSeeder
<?php
use Illuminate\Database\Seeder;
class ArticalesTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
factory(App\Article::class,30)->create();
}
}
ArticleFactory.php
<?php
/* @var $factory \Illuminate\Database\Eloquent\Factory */
use Faker\Generator as Faker;
$factory->define(App\Article::class, function (Faker $faker) {
return [
'title' => $faker->text(50),
'body' => $faker->text(200)
];
});
App \ Resources \ Article.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Article extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return parent::toArray($request);
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$this->call(ArticalesTableSeeder::class);
}
}
routes / api.php
//list
Route::get('articles','ArticleController@index');
//list single
Route::get('article/{id}','ArticleController@show');
//create article
Route::post('article','ArticleController@store');
//update articles
Route::put('article','ArticleController@store');
//delete article
Route::delete('articles','ArticleController@destroy');
答案 0 :(得分:1)
Laravel会自动在HWND
文件中的路由前面加上路由前缀routes/api.php
您需要请求以下内容:
/api
而不是
http://127.0.0.1:8000/api/articles
如果您愿意,可以在http://127.0.0.1:8000/articles
中进行更改:
https://github.com/laravel/laravel/blob/master/app/Providers/RouteServiceProvider.php#L66-L72