<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Books; //เรียก Model เข้ามาใช้งาน
use App\Http\Requests\StoreBooksRequest;
use Image; //เรียกใช้ Library จัดการรูปภาพเข้ามาใช้งาน
use Illuminate\Support\Str;//นำ Helpers String เข้ามาใช้งาน
class BooksController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$books = Books::with('typebooks')->orderBy('id','desc')->paginate(3);
return view('books/index',['books' => $books]);
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('books.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(StoreBooksRequest $request)
{
$book = new books();
$book->name_book = $request->name_book;
$book->price = $request->price;
$book->typebooks_id = $request->typebooks_id;
//upload image
if($request->hasFile('image')){
$filename = Str::random(10).'.'.$request->file('image')->getClientOriginalExtension();
$request->file('image')->move(public_path().'/images'.$filename);
Image::make(public_path().'/images/'.$filename)->resize(50,50)->save(public_path().'/images/resize/'.$filename);
$book->image = $filename;
}else{
$book->image = 'nopic.jpg';
}
//$book->save();
return redirect()->action('BooksController@index');
}
}
Route Code (PHP)
//Books ตั้งชื่อ Method index ว่า books
Route::resource('books','BooksController')->name('index','books');