composer create-project laravel/lumen --prefer-dist Lumen
DB_CONNECTION=mysql DB_USERNAME=homestead DB_PASSWORD=secret DB_DATABASE=lumen
php artisan make:migration create_users_table php artisan make:migration create_posts_table
//database/*create_users_table.php Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('email')->unique(); $table->string('first_name'); $table->string('last_name'); $table->string('password'); $table->rememberToken(); $table->timestamps(); $table->softDeletes(); });
//database/*create_posts_table.php Schema::create('posts', function (Blueprint $table) { $table->increments('id'); $table->string('user_id'); $table->string('content'); $table->timestamps(); $table->softDeletes(); });
php artisan migrate
Dotenv::load(__DIR__.'/../');
use Illuminate\Database\Eloquent\Model; class Post extends Model { /** * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function user() { return $this->belongsTo('Written\Models\User'); } }
/** * @Middleware("auth.token") * @Resource('post') */ class PostsController extends Controller { public function index() {} public function show($id) {} public function store() {} public function update() {} public function destroy() {} }
$app->get('/', function() use ($app) { return $app->welcome(); }); $app->post('/register', ['uses' => 'App\Http\Controllers\AuthController@postRegister']); $app->post('/login', ['uses' => 'App\Http\Controllers\AuthController@postLogin']); $app->get('/post/{id}', ['uses' => 'App\Http\Controllers\PostsController@show']); $app->get('/post', ['uses' => 'App\Http\Controllers\PostsController@index']); $app->group(['middleware' => 'logged.in'], function($app) { $app->post('/post', ['uses' => 'App\Http\Controllers\PostsController@store']); /** & another protected routes */ });
//app/Http/Middlewared/LoggedInMiddleware.php class LoggedInMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { if(!Auth::check()) { return new Response('', 401); } return $next($request); } }
//app/Http/Controller/PostsController.php /** * Class PostsController * @package App\Http\Controllers */ class PostsController extends Controller { public function index() { return $this->respondWithData(Post::with('user')->all()->toArray()); } public function show($id) { return $this->respondWithData(Post::find($id)->with('user')->get()->toArray()); } public function store() { $rules = [ 'text' => 'required', ]; $input = $_POST; $validator = Validator::make($input, $rules); if ($validator->fails()) { return $this->respondWithFailedValidation($validator); } $post = new Post; $post->content = $input['content']; $post->user()->associate(Auth::user()); $post->save(); return $this->show($post->id); } // public function delete() {} }
Source: https://habr.com/ru/post/257073/
All Articles