Eshop-Laravel/app/Categorie.php

73 lines
2 KiB
PHP
Raw Permalink Normal View History

2019-10-18 09:25:37 +00:00
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Session , Image , DB;
class Categorie extends Model
{
public function products (){
return $this -> hasMany('App\Product');
}
static public function save_new($request){
$img = self::loadImage($request);
//defult Image
$image_name = $img ? $img : 'noimage.png';
//save the pic in the DB
$category = new self();
$category ->title = $request['title'];
$category ->article = $request['title'];
$category ->url = $request['url'];
$category ->image = $image_name;
$category ->save();
Session::flash('sm' , 'Category As been Saved!');
}
static public function find_item($id){
$sql = 'SELECT * FROM categories c WHERE c.id = ?';
$item = DB::select($sql,[$id] );
return $item;
}
static public function update_item($request , $id){
$image_name =self::loadImage($request);
//save the pic in the DB
$category = self::find($id);
$category ->title = $request['title'];
$category ->article = $request['title'];
$category ->url = $request['url'];
if ($image_name) {
$category ->image = $image_name;
}
$category ->save();
Session::flash('sm' , 'Category As been Updated!');
}
static private function loadImage($request){
$image_name = '';
if ($request->hasFile('image') && $request->file('image')->isValid()) {
//take the user pic to our server
$file = $request->file('image');
$image_name = date('Y.m.d.H.i.s') . '-' . $file->getClientOriginalName();
$request->file('image')->move( public_path() . '/images' , $image_name);
//take the origin pic and make a new one by using Image Class to provent viruses
$img = Image::make(public_path() . '/images'.'/' . $image_name);
//resize the pic to 300 Width
$img->resize(300, null, function ($constraint) {
$constraint->aspectRatio();
});
//save the new pic and overWrite the pic
$img ->save(public_path() . '/images'.'/' . $image_name);
}
return $image_name;
}
}