GithubHelp home page GithubHelp logo

danielarturoalejoalvarez / restfull-laravel-8.5-eloquent-api-resources Goto Github PK

View Code? Open in Web Editor NEW
14.0 2.0 4.0 1.49 MB

Software of Application with Laravel(RESTFull API)

Shell 0.68% PHP 79.98% Blade 18.98% Vue 0.36%
laravel mysql vuejs bootstrap eloquent

restfull-laravel-8.5-eloquent-api-resources's Introduction

RESTFull API LARAVEL + VUE

Description

This repository is a Software of Development with Laravel,MySQL,VUE,Axios,Boostrap,etc

Installation

Using Laravel 8.5 and Vue.js 2.5 preferably.

DataBase

Using MySQL preferably. Create a MySQL database and configure the .env file.

Apps

Using Postman,Talend API Tester,Insomnia,etc

Usage

$ git clone https://github.com/DanielArturoAlejoAlvarez/RESTFull-Laravel-8.5-Eloquent-API-Resources[NAME APP]

$ composer install

$ copy .env.example .env

$ php artisan key:generate

$ php artisan migrate:refresh --seed

$ php artisan serve

$ npm install (Frontend)

$ npm run dev

Follow the following steps and you're good to go! Important:

alt text

Coding

Component

...
import axios from 'axios';

    export default {
       data() {
           return {
               posts: null
           }
       },
       mounted() {
           this.getPosts()
       },
       methods: {
           getPosts: function() {
            axios.get('api/posts')
                .then(res=>{
                    this.posts = res.data
                })
            }
       }
       
    }
...

Controllers

...
class PostController extends Controller
{

    protected $post;

    /**HTTP Status
     * 1XX Info
     * 2XX Respose Successfully
     * 3XX Redirection
     * 4XX Error Client
     * 5XX Error Server
     */

    public function __construct(Post $post)
    {
        $this->post = $post;
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return response()->json(
            new PostCollection(
                $this->post->orderBy('id', 'DESC')->get()
            )
        );
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(PostRequest $request)
    {

        $post = $this->post->create($request->all());
        return response()->json(new PostResource($post), 201);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function show(Post $post)
    {

        return response()->json(new PostResource($post), 200);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function update(PostRequest $request, Post $post)
    {
        $post->update($request->all());
        return response()->json(new PostResource($post));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Post  $post
     * @return \Illuminate\Http\Response
     */
    public function destroy(Post $post)
    {
        $post->delete();
        /**
         * VerifyCsrfToken apply except api/*
         */
        return response()->json(null, 204);
    }
}
...

Models

...
class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title','body'];

}
...

Resources

...
class Post extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        //return parent::toArray($request);
        return [
            'id'            =>  $this->id,
            'post_name'     =>  strtoupper($this->title),
            'post_body'     =>  strtoupper(substr($this->body,0,100)) . '...',
            'published_at'  =>  $this->created_at->diffForHumans(),
            'created_at'    =>  $this->created_at->format('d-m-Y'),
            'updated_at'    =>  $this->updated_at->format('d-m-Y'),
        ];
    }
}
...

Middlewares

...
class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'api/*'
    ];
}
...

Routes

...

#API
Route::apiResource('posts', App\Http\Controllers\Api\PostController::class)->names([
  'index'   =>  'api.posts.index',
  //'store'   =>  'api.posts.store',
  //'show'    =>  'api.posts.show',
  //'update'  =>  'api.posts.update',
  //'destroy' =>  'api.posts.destroy',
])->only('index');

#WEB
Route::get('/', [App\Http\Controllers\PageController::class, 'index'])->name('welcome');

Route::group(['prefix' => 'api'], function () {
    //Route::apiResource('posts', PostController::class);
});

Route::middleware('auth')->resource('posts', App\Http\Controllers\Backend\PostController::class)->only('index');

Route::get('/home', [App\Http\Controllers\Backend\HomeController::class, 'index'])->name('home');

Auth::routes();

...

Factory

...
public function definition()
    {
        return [
            'title' =>  $this->faker->sentence,
            'body'  =>  $this->faker->text,
        ];
    }
...

Seeders

...
public function run()
    {
        // \App\Models\User::factory(10)->create();
        \App\Models\User::create([
            'name'      =>  [YOUR NAME],
            'email'     =>  [YOUR EMAIL],
            'password'  =>  bcrypt([YOUR PASSWORD])
        ]);

        \App\Models\Post::factory(18)->create();
    }
...

HTTP Resources

$ http://127.0.0.1:8000/posts (frontend/backend[auth])

$ http://127.0.0.1:8000/api/posts (API)

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/DanielArturoAlejoAlvarez/RESTFull-Laravel-8.5-Eloquent-API-Resources. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the Contributor Covenant code of conduct.

License

The gem is available as open source under the terms of the MIT License.


restfull-laravel-8.5-eloquent-api-resources's People

Contributors

danielarturoalejoalvarez avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.