2020-12-21 07:09:34 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
|
2020-12-26 10:46:23 +00:00
|
|
|
use App\Models\Author;
|
|
|
|
use App\Models\Book;
|
|
|
|
use App\Models\Location;
|
|
|
|
use Illuminate\Http\Request;
|
|
|
|
use Illuminate\Support\Arr;
|
|
|
|
|
2020-12-21 07:09:34 +00:00
|
|
|
class MainController extends Controller {
|
|
|
|
public function index() {
|
2020-12-26 10:46:23 +00:00
|
|
|
$rows = Book::paginate(15);
|
|
|
|
|
|
|
|
return view('index', [ 'rows' => $rows ]);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function search(Request $request) {
|
|
|
|
$this->validate($request, [
|
|
|
|
'query' => [ 'required' ]
|
|
|
|
]);
|
|
|
|
|
|
|
|
$rows = Book::where('name', 'LIKE', '%' . $request->get('query') . '%')->paginate(15);
|
|
|
|
|
|
|
|
return view('index', [ 'rows' => $rows ]);
|
|
|
|
}
|
|
|
|
|
|
|
|
public function add(Request $request) {
|
|
|
|
return view('add', [
|
|
|
|
'old' => array_filter($request->old('books', []), function($item) {
|
|
|
|
return !empty($item['barcode']);
|
|
|
|
})
|
|
|
|
]);
|
2020-12-21 07:09:34 +00:00
|
|
|
}
|
|
|
|
|
2020-12-26 10:46:23 +00:00
|
|
|
public function save(Request $request) {
|
|
|
|
$this->validate($request, [
|
|
|
|
'location' => [ 'required' ]
|
|
|
|
]);
|
|
|
|
|
|
|
|
$input = array_filter($request->get('books'), function($item) {
|
|
|
|
return !empty($item['barcode']) && !empty($item['name']);
|
|
|
|
});
|
|
|
|
|
|
|
|
$this->getValidationFactory()->make($input, [
|
|
|
|
'*.barcode' => [ 'required' ],
|
|
|
|
'*.name' => [ 'required' ]
|
|
|
|
]);
|
|
|
|
|
|
|
|
$location = Location::firstOrCreate([
|
|
|
|
'name' => trim($request->get('location'))
|
|
|
|
]);
|
|
|
|
|
|
|
|
foreach ($input as $item) {
|
|
|
|
$book = Book::create([
|
|
|
|
'location_id' => $location->id,
|
|
|
|
'barcode' => $item['barcode'],
|
|
|
|
'name' => $item['name']
|
|
|
|
]);
|
|
|
|
|
|
|
|
$authors = [];
|
|
|
|
|
|
|
|
foreach (Arr::get($item, 'authors') as $author) {
|
|
|
|
$authors[] = Author::firstOrCreate([
|
|
|
|
'name' => $author
|
|
|
|
]);
|
|
|
|
}
|
|
|
|
|
|
|
|
$authors = array_map(function($author) { return $author->id; }, $authors);
|
|
|
|
|
|
|
|
$book->authors()->attach($authors);
|
|
|
|
}
|
2020-12-21 07:09:34 +00:00
|
|
|
}
|
|
|
|
}
|