shareit/app/Http/Controllers/ProductController.php

79 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace App\Http\Controllers;
use \App\Item;
use \App\User;
use \App\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
public function index()
{
$products = Product::fromAuthUser()->get();
return view('product.index', compact('products'));
}
/**
* Stores the included product into database
*
* @return (view) The product view
*/
2018-09-16 23:32:32 +00:00
public function store(Request $request)
{
2018-09-16 23:32:32 +00:00
$request->validate(['product' => 'required']);
Product::create(['name' => request('product'), 'user_id' => \Auth::id(), 'url' => request('url') ?? '']); //Just remember to add the fillable on Model to make this work
return redirect('product');
}
/**
* Delete a specified Product
*
* @param (int) $id The product id
*/
2018-09-16 23:32:32 +00:00
public function delete(Request $request)
{
2018-09-16 23:32:32 +00:00
$request->validate(['product' => 'required']);
$product = User::loggedIn()
->products()->with('items')->find(request('product'));
2018-09-16 23:32:32 +00:00
//Detach users from this item
foreach ($product->items as $item) {
Item::deleteAndDetach($item);
2018-09-16 23:32:32 +00:00
}
//Delete product
$product->delete();
return redirect('product');
2018-09-16 23:32:32 +00:00
}
public function patch(Request $request)
{
2018-09-16 23:43:14 +00:00
$request->validate(['product' => 'required', 'name' => 'required']);
$product = User::loggedIn()->products()->find(request('product'));
2018-09-16 23:43:14 +00:00
$product->name = request('name');
$product->url = request('url');
$product->save();
return redirect('product/' . request('product'));
}
/**
* Show a specified Product
*
* @param (int) $id The product id
*
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$product = Product::fromAuthUser()->find($id);
if (!$product) {
session()->flash('danger', "The product doesn't exist or doesn't belongs to you.");
return redirect('/product');
}
2018-09-11 23:48:09 +00:00
return view('product.show', compact('product'));
}
}