2018-09-09 03:26:57 +00:00
< ? php
namespace App\Http\Controllers ;
use Illuminate\Http\Request ;
use \App\Product ;
2018-09-10 04:23:32 +00:00
use \App\User ;
2018-09-09 03:26:57 +00:00
class ProductController extends Controller
{
public function index ()
{
2018-09-12 05:31:03 +00:00
$products = Product :: where ( 'user_id' , \Auth :: id ()) -> get ();
2018-09-10 04:23:32 +00:00
return view ( 'product.index' , compact ( 'products' ));
2018-09-09 03:26:57 +00:00
}
2018-09-10 04:23:32 +00:00
/**
* 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-10 04:23:32 +00:00
{
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
2018-09-10 04:23:32 +00:00
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-10 04:23:32 +00:00
{
2018-09-16 23:32:32 +00:00
//TODO: Delete all items with all users for the product
$request -> validate ([ 'product' => 'required' ]);
2018-09-16 23:43:14 +00:00
$item = User :: findOrFail ( \Auth :: id ())
2018-09-16 23:32:32 +00:00
-> items () -> with ( 'users' ) -> find ( request ( 'item' ));
$product = $item -> product_id ;
//Detach users from this item
foreach ( $item -> users as $user ) {
User :: findOrFail ( $user -> id ) -> items () -> detach ( $item -> id );
}
//Delete item
$item -> delete ();
return redirect ( 'product/' . $product );
}
public function patch ( Request $request )
{
2018-09-16 23:43:14 +00:00
$request -> validate ([ 'product' => 'required' , 'name' => 'required' ]);
$product = User :: find ( \Auth :: id ()) -> products () -> find ( request ( 'product' ));
$product -> name = request ( 'name' );
$product -> url = request ( 'url' );
$product -> save ();
return redirect ( 'product/' . request ( 'product' ));
2018-09-10 04:23:32 +00:00
}
/**
* Show a specified Product
*
* @ param ( int ) $id The product id
*/
2018-09-09 03:26:57 +00:00
public function show ( $id )
{
2018-09-12 05:31:03 +00:00
$product = Product :: where ( 'user_id' , \Auth :: id ()) -> find ( $id );
2018-09-11 23:48:09 +00:00
return view ( 'product.show' , compact ( 'product' ));
2018-09-09 03:26:57 +00:00
}
}