API Newspaper – Laravel

composer create-project laravel/laravel newspapers

Migración / Migration

sudo php artisan make:migration migration_notice
sudo php artisan make:migration migration_theme

database/migrations/2019_10_27_225656_migration_notice.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class MigrationNotice extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::create('post', function (Blueprint $table) {
           $table->increments('id');
           $table->string('title',500);
           $table->string('article',2000);
           $table->string('image',200);
           $table->integer('theme');
           $table->timestamps();
        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

database/migrations/2019_10_27_230602_migration_theme.php

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class MigrationTheme extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
        Schema::create('theme', function (Blueprint $table) {
           $table->increments('id');
           $table->string('name');
        });

    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

Ejecutar migración

php artisan migrate

Modelos / Models

php artisan make:model Models/Post
php artisan make:model Models/Theme

app/Models/Post.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    //
    protected $table = "post";

    protected $fillable = [
      'title',
      'article',
      'image',
      'theme'
    ];

    public function theme()
    {
      return $this->belongsTo('App\Models\Theme', 'theme', 'id');  
    }
    // public $timestamps = false;
}

app/Models/Theme.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Theme extends Model
{
    //
    protected $table = "theme";

}

Controlador / Controllers

php artisan make:controller NewspaperController

app/Http/Controllers/NewspaperController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Models\Post;
use App\Models\Theme;
use Log;

class NewspaperController extends Controller
{
    //
    public function index(){
      $post = Post::join('theme', 'theme.id', 'post.theme')
      ->get();
      return view('news/index',[
        'post' => $post
      ]);
      return view('news/index');
    }

    public function form(){
      $theme = Theme::get();
      return view('news/form',[
        'theme' => $theme
      ]);
    }

    public function create(Request $request)
    {

      $request->validate([
          'title' => 'required|max:255',
          'article' => 'required|max:2000',
          'theme' => 'required'
      ]);

      $file  = $request->file('image');
      $route = $file->store('post','public');

      $insert['title'] = $request->input("title");
      $insert['article'] = $request->input("article");
      $insert['theme'] = $request->input("theme");
      $insert['image'] = $route;

      $res = Post::create($insert);
      return redirect('news/index');
    } 

}

Vistas / Views

resources/views/news/form.blade.php

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Jekyll v3.8.5">
    <title>Album example · Bootstrap</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/album/">

    <!-- Bootstrap core CSS -->
<link href="https://getbootstrap.com/docs/4.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <!-- Custom styles for this template -->
    <link href="album.css" rel="stylesheet">
  </head>
  <body>
    <header>

      <div class="navbar navbar-dark bg-dark shadow-sm">
        <div class="container d-flex justify-content-between">
          <a href="index" class="navbar-brand d-flex align-items-center">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true" class="mr-2" viewBox="0 0 24 24" focusable="false"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
            <strong>Newspaper</strong>
          </a>
        </div>
      </div>
    </header>

<main role="main">

  <div class="album py-5 bg-light">
    <div class="container">

      <div class="row">
        <div class="col-md-12">

          @if ($errors->any())
              <div class="alert alert-danger">
                  <ul>
                      @foreach ($errors->all() as $error)
                          <li>{{ $error }}</li>
                      @endforeach
                  </ul>
              </div>
          @endif

          <form  method="POST" action="create" enctype="multipart/form-data">
            @csrf
            <div class="form-group">
              <label for="exampleFormControlInput1">Title</label>
              <input type="text" class="form-control" name="title"  >
            </div>
            <div class="form-group">
              <label for="exampleFormControlTextarea1">Article</label>
              <textarea class="form-control" name="article" rows="3"></textarea>
            </div>

            <div class="input-group">
              <div class="input-group-prepend">
                <span class="input-group-text" id="inputGroupFileAddon01">Upload</span>
              </div>
              <div class="custom-file">
                <input type="file" class="custom-file-input" id="inputGroupFile01" name="image"
                  aria-describedby="inputGroupFileAddon01">
                <label class="custom-file-label" for="inputGroupFile01">Choose file</label>
              </div>
            </div>
            <br>
            <div class="form-group">
              <label for="exampleFormControlSelect1">Theme</label>
              <select class="form-control" name="theme">
                @foreach ($theme as $them)
                    <option value="{{ $them->id }}">{{ $them->name }}</option>
                @endforeach

              </select>
            </div>

            <button type="submit" class="btn btn-primary ">Publish</button>

          </form>

        </div>

      </div>
    </div>
  </div>

</main>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
      <script>window.jQuery || document.write('<script src="/docs/4.3/assets/js/vendor/jquery-slim.min.js"><\/script>')</script><script src="/docs/4.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-xrRywqdh3PHs8keKZN+8zzc5TX0GRTLCcmivcbNJWm2rs5C8PRhcEn3czEjhAO9o" crossorigin="anonymous"></script></body>
</html>

resources/views/news/index.blade.php

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Jekyll v3.8.5">
    <title>Album example · Bootstrap</title>

    <link rel="canonical" href="https://getbootstrap.com/docs/4.3/examples/album/">

    <!-- Bootstrap core CSS -->
    <link href="https://getbootstrap.com/docs/4.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

  </head>
  <body>
    <header>

      <div class="navbar navbar-dark bg-dark shadow-sm">
        <div class="container d-flex justify-content-between">
          <a href="#" class="navbar-brand d-flex align-items-center">
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" aria-hidden="true" class="mr-2" viewBox="0 0 24 24" focusable="false"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
            <strong>Newspaper</strong>
          </a>

          <a href="form" class="btn btn-primary my-2 pull-right">Publish news</a>

        </div>
      </div>
    </header>

<main role="main">


  <div class="album py-5 bg-light">
    <div class="container">

      <div class="row">

        @foreach ($post as $postitem)
        <div class="col-md-4">
          <div class="card mb-4 shadow-sm">
            <!-- <svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: Thumbnail"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">Thumbnail</text></svg> -->
            <img src="{{ asset('storage/'.$postitem->image) }}" width="100%" height="225"  alt="Image">

            <div class="card-body">
              <h4 class="text-truncate">{{$postitem->title}}</h4>
              <p class="card-text text-truncate">
                {{$postitem->article}}
              </p>
              <div class="d-flex justify-content-between align-items-center">
                <small class="text-muted">{{$postitem->name}}</small>
                <div class="btn-group">
                  <button type="button" class="btn btn-sm btn-outline-secondary">View</button>
                </div>
              </div>
            </div>
          </div>
        </div>
        @endforeach

      </div>
    </div>
  </div>

</main>

<footer class="text-muted">
  <div class="container">
    <p class="float-right">
      <a href="#">tutofox.com</a>
    </p>
    </div>
</footer>
</html>

Route

routes/web.php

Route::get('/','NewspaperController@index');
Route::get('news/index','NewspaperController@index');
Route::get('news/form','NewspaperController@form');
Route::post('news/create','NewspaperController@create');

API

php artisan make:controller API/NewsController

app/Http/Controllers/API/NewsController.php

<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\Theme;

class NewsController extends Controller
{
    //
    public function api(){
      $response['news']  = Post::join('theme', 'theme.id', 'post.theme')->get();
      $response['theme'] = Theme::get();
      $response['banner'] = Post::join('theme', 'theme.id', 'post.theme')->limit(3)->inRandomOrder()->get();
      return $response;
    }
}

routes/api.php

Route::get('news','API\NewsController@api');

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *