I have an Image model it saves data through the controller but it doesn't display data, please what's the issue.
The Model
namespace App;
use App\Event\NotifyPhoto;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public $table = "images";
protected $guarded = [];
public $timestamps = false;
public function property_user()
{
return $this->belongsTo('App\PropertyUser');
}
public function facility(){
return $this->belongsTo('App\Facility');
}
}
The Image controller
namespace App\Http\Controllers;
use App\Http\Requests\ImageRequest;
use App\Property;
use App\PropertyUser;
use Illuminate\Http\Request;
use App\Facility;
use App\Image;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Carbon;
class ImageController extends Controller
{
public function create()
{
dd(Image::all());//This comes back empty
return view('settings.photos');
}
public function store(Request $request)
{
$property_users = PropertyUser::where('user_id', '=', Auth::user()- >id)->get();
foreach ($property_users as $property_user) {
$id = $property_user->property_id;
}
$rules = [
'file' => 'required',
'description' => 'required',
'tag' => 'required'
];
$request->file('file');
if (!empty($request->file('file'))) {
$file_count = count($request->file('file'));
} else $file_count = null;
foreach (range(0, $file_count) as $index) {
$rules['file.' . $index] = 'image|mimes:jpeg,gif,webp,bmp,png|max:2048';
}
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
} else {
$files = $request->file('file');
$description = $request->input('description');
$tag = $request->input('tag');
$i = 0;
foreach ($files as $file) {
$i++;
$file1 = $file->move(public_path() . '/upload_images/', $file->getClientOriginalName());
$url1 = $url = URL::to("/") . '/upload_images/' . $file->getClientOriginalName();
$image = Image::create([
'filename' => $url,
'description' => $description,
'facility_id' => 16, //$new_fac->id ?? $f->id,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
'tag' => $tag
]);
dd($image);//This displays the files saved and their ids in the table
]
}
return redirect('settings/photos');
}
}
}
Try adding this to your App/Image:
protected $fillable = [
'filename',
'description',
'facility_id',
'created_at',
'updated_at',
'tag',
];
https://laravel.com/docs/5.6/eloquent#mass-assignment
Also, can you confirm a new row is being added to the database?
Related
I'm facing a weird problem that only accurs when I use pagination with livewire components,
this is the error:
BadMethodCallException
Method Illuminate\Support\Collection::items does not exist.
I know what this errors means, the problem is why it only accurs when I change page in pagination:
this is my Component:
<?php
namespace App\Http\Livewire\Admin;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
use App\Models\Product;
use App\Models\Category;
use File;
use GlobalsHelper;
class Products extends Component
{
use WithPagination, WithFileUploads;
public $products;
public $subcategories;
// Form
public $name;
public $description;
public $price;
public $quantity;
public $category_id = null;
public $sub_category_id = null;
public $image;
public $selected = [];
public $query = '';
public $filter_by_category = '';
protected $paginationTheme = 'bootstrap';
public function render()
{
$pagination = $this->products;
$this->products = collect($this->products->items());
return view('livewire.admin.products', [
'categories' => Category::all(),
'subcategories' => $this->subcategories,
'products' => $this->products,
'pagination' => $pagination
]);
}
// public function render()
// {
// return view('livewire.admin.products', [
// 'categories' => Category::all(),
// 'subcategories' => $this->subcategories,
// 'products' => $this->products,
// ]);
// }
public function mount()
{
$this->getSubcategories();
$this->index();
}
public function getSubcategories()
{
$this->subcategories = [];
if ( !$this->category_id )
{
$this->category_id = (Category::first()) ? Category::first()->id : null;
}
$category = Category::find($this->category_id);
if ( !$category )
{
return null;
}
$this->subcategories = $category->children;
$this->sub_category_id = ($this->subcategories->first()) ? $this->subcategories->first()->id : null;
}
public function store()
{
$fields = $this->validate([
'name' => ['required', 'string', 'min:5', 'max:250'],
'description' => ['string', 'max:250'],
'price' => ['required', 'numeric', 'min:1'],
'quantity' => ['required', 'numeric', 'min:1'],
'category_id' => ['nullable'],
'sub_category_id' => ['nullable'],
]);
$fields['user_id'] = GlobalsHelper::auth()->id;
$product = Product::create($fields);
if ( !$product )
{
session()->flash('error', __('messages.error_create'));
return;
}
// upload image
$this->storeImage($product);
$this->resetFields();
session()->flash('success', __('messages.success_create'));
}
public function search()
{
$results = Product::where('name', 'LIKE', '%'.$this->query.'%')
->orderBy('id', 'desc')->paginate(5);
$this->products = $results;
}
public function index()
{
$this->products = Product::orderBy('id', 'desc')->paginate(5);
}
public function filterByCategory()
{
$results = Product::where('category_id', '=', $this->filter_by_category)
->orderBy('id', 'desc')->paginate(5);
$this->products = $results;
}
// private
private function resetFields()
{
$this->name = null;
$this->description = null;
$this->price = 0;
$this->quantity = 1;
$this->image = null;
$this->filename = '...';
}
private function storeImage($product)
{
$this->validate([
'image' => ['nullable', 'image', 'max:1024'],
]);
if ( $this->image )
{
// Delete old image if exists
if ( $product->image )
{
File::delete([$product->image->fullpath]);
}
$filename = sha1( uniqid('', true) );
$ext = $this->image->getClientOriginalExtension();
$fullpath = $this->image->store(GlobalsHelper::PRODUCTS_UPLOADS_DIR.'/'.$product->id, 'public');
$product->update([
'image' => [
'name' => basename($fullpath),
'type' => $ext,
'fullpath' => GlobalsHelper::STORAGE_DIR.$fullpath,
'url' => asset(GlobalsHelper::STORAGE_DIR.$fullpath)
]
]);
}
}
}
The idea is that I want to achieve search, store, update, delete, filter operations in same compoenent like in laravel controller, I found solutions online, but only 50% of what I need to achieve.
I have been wasting a lot of time trying to figure this out.
If any one would help me, I will be much appreciated.
At first glance without seeing the view, you are getting the $produts via the mount() method, this will only run ONCE when the livewire component is first rendered. From the docs:
mount() is only ever called when the component is first mounted and will not be called again even when the component is refreshed or rerendered.
This is my Item model. I have made a function arrayPackageItemSelect that gets the id and equivalent it to the item name.
class Item extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'name',
'price',
'itemdescription',
'activeInactive'
];
public function packageitems()
{
return $this->hasMany(PackageItem::class);
}
public static function arrayPackageItemSelect()
{
$arr = [];
$items = Item::all();
foreach($items as $item){
$arr[$item->id] = $item->name;
}
return $arr;
}
}
my PackageItem Model
class PackageItem extends Model
{
protected $fillable = [
'user_id',
'item_id',
'price'
];
protected $table='packageitems';
public static function itemModel()
{
return $this->belongsTo(Item::class);
}
}
my PackageItem Controller (CREATE) and getting the Item ID from another table (Foreign key) so I can put a category for it.
public function addPackageItem(Request $request)
{
$user = Auth::user();
$item = Item::arrayPackageItemSelect();
echo $item; // when I echo this I get Array to Conversion String in POSTMAN
$fields = $request->validate([
'user_id' => 'required',
'item_id' => 'required',
'price' => 'required|numeric'
]);
// // echo $items;
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => $item,
'price'=> $fields['price']
]);
return response($package, 201);
}
What I get when I echo the Items
The results I get from POSTMAN
My Schema
This is where my reference is https://www.artofcse.com/learning/product-view-insert-update-delete
Can anybody help me what is wrong?
In your controller (addPackageItem method):
$package = PackageItem::create([
'user_id' => $user->id,
'item_id' => $fields['item_id'],
'price'=> $fields['price']
]);
Also, i think there is an error in your PackageItem model. belongsTo should not be called in a static method :
public function itemModel()
{
return $this->belongsTo(Item::class);
}
I am sending two different emails. One from VerifyMail and other from ForgetEmail but laravel throws error that VerifyMail does not exits. It was working just fine when i had not added the ForgetMail class.
This is my code where i am using VerifyMail
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\User;
use App\VerifyUser;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Carbon;
use App\Mail\VerifyMail;
class UserRegisterController extends Controller
{
public function __construct()
{
$this->middleware('guest:user');
}
public function showRegisterForm() {
return view('user.registerForm');
}
public function register(Request $request) {
$userValidated = $this->validate($request, [
'name' => 'required|string',
'email' => 'required|string|unique:users',
'password' => 'required|string|min:6|confirmed'
]);
$register = [
'name' => $userValidated['name'],
'email' => $userValidated['email'],
'password' => Hash::make($userValidated['password']),
];
$user =User::create($register);
VerifyUser::create([
'token' => str::random(60),
'user_id' => $user->id,
]);
Mail::to($user->email)->send(new VerifyMail($user));
return redirect('user/login')->with('email', 'An email was sent to you for verification');
}
public function verifyEmail($token, $date) {
$dates = date(strtotime($date));
if(time() - $dates > 60 * 60) {
return redirect('/user/login')->with('failed' , 'Oops! Something went wrong');
}
$verifiedUser = VerifyUser::where('token', $token)->first();
if(isset($verifiedUser)) {
$user = $verifiedUser->user;
if($user->email_verified_at == '') {
$user->email_verified_at = carbon::now();
$user->save();
return redirect('/user/login')->with('success', 'Your email was successfully verified');
} else {
return redirect('/user/login')->with('failed' , 'Oops! Something went wrong');
}
}
}
}
This is the code where i am using ForgetEmail
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
// use Symfony\Component\HttpFoundation\Session\Session;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Session;
use App\ForgetPassword;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;
use App\Mail\ForgetEmail;
use App\User;
use Illuminate\Support\Facades\Hash;
class UserLoginController extends Controller
{
protected $guard;
use AuthenticatesUsers;
public function __construct()
{
$this->middleware('guest:user')->except('logout');
$this->guard = Auth::guard('user');
}
public function showLoginForm()
{
return view('user.login');
}
public function forgetPasswordForm() {
return view('user.forget');
}
public function passwordResetForm($id) {
$user = User::where('id', $id)->first();
return view('user.resetForm', ['id' => $id]);
}
public function userLogin(Request $request) {
$validated = $this->validate($request, [
'email' => 'required|email',
'password' => 'required|min:6',
]);
if(Auth::guard('user')->attempt(['email' => $validated['email'], 'password' => $validated['password']], $request->remember)) {
$user = Auth::guard('user')->user();
if($user->email_verified_at != null) {
return redirect()->route('user.dashboard');
} else {
$this->logout($msg = 1);
}
}
return redirect()->back();
}
public function forgetPassword(Request $request) {
$email = $this->validate($request, [
'email' => 'required|email|exists:users',
]);
$forgetPass = User::where('email', $email['email'])->first();
$forgetArray = array(
'user_id' => $forgetPass->id,
'token' => str::random(60),
);
$forgetPassword = ForgetPassword::create($forgetArray);
Mail::to($email['email'])->send(new ForgetEmail($forgetPassword->user));
return redirect('user/forgetPassword')->with('email', 'We have sent you an email to reset your password');
}
public function passwordReset($token, $date) {
$checkTime = strtotime($date);
if(time() - $checkTime > 20 * 60) {
return redirect('user/login/')->with('passes', 'Looks like the link has expired');
}
$passReset = ForgetPassword::where('token', $token)->first();
if(isset($passReset)) {
$user = $passReset->user;
if($user->password) {
return redirect('/user/passwordReset'. '/'. $user->id);
}
}
}
public function passwordUpdate(Request $request, $id) {
$validatePass = $this->validate($request, [
'password' => 'required|string|min:6|confirmed',
]);
$pass = User::where('id', $id)->first();
$pass->password = Hash::make($validatePass['password']);
$pass->save();
return redirect('/user/login')->with('reset', 'Your password has been reset');
}
public function logout($msg = 0) {
$cookieName = $this->guard->getRecallerName();
$cookie = Cookie::forget($cookieName);
Auth::logout();
Session::flush();
if($msg == 0) {
return redirect()->route('user.login')->withCookie($cookie);
} else {
return redirect()->route('user.login')->withCookie($cookie)->with('verify', 'Your email is not verified');
}
}
}
All of my code was working fine before when i had not added that ForgetEmail class in Mail. I don't know what's the problem here. Will be glad if you can find it for me.
I am trying to insert image in database using laravel 5.4. It works. But when I search that directory then it does not appear there. I also want to validate only images should be upload and size.
Thanks for advance.
My Controller function is here
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Hash;
use App\User;
class regController extends Controller
{
public function create(Request $request)
{
$this-> validate(request(),[
'name' => 'required',
'email'=> 'required',
'type' => 'required',
'image' => 'required',
'password' => 'required|confirmed|min:6',
]);
$request['password'] = bcrypt($request -> password);
$User = new User($request->input()) ;
if($file = $request->hasFile('image')) {
$file = $request->file('image') ;
$fileName = $file->getClientOriginalName() ;
return Storages::putFile('public/images',$request->file('image'));
$destinationPath = public_path().'images/' ;
$file->move($destinationPath,$fileName);
$User->image = $fileName ;
}
$user =
User::create(request(['name','email','type','image','password']));
return redirect('login');
}
try this :
// Validation
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,bmp,png|max:10240' // size in kelobytes this equals 10 mb
]);
$User = new User() ;
$User->password = bcrypt($request->password);
$User->name = $request->name;
$User->type = $request->type;
$User->email = $request->email;
$filename = $this->getFileName($request->image);
$request->image->move(base_path('public/images'), $filename);
$User->image = $fileName;
$$User->save();
return back()->with('success','Image Upload successful');
I just forgot to show you how to implement getFileName function to generate a unique filename sorry about that, in your controller you can define it as protected method like so:
protected function getFileName($file)
{
return str_random(32) . '.' . $file->extension();
}
I think you are tryin to do smth like this:
public function fileUpload(Request $request)
{
$this->validate($request, [
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$image = $request->file('image');
$input['imagename'] = time().'.'.$image->getClientOriginalExtension();
$destinationPath = public_path('/images');
$image->move($destinationPath, $input['imagename']);
$this->postImage->add($input);
return back()->with('success','Image Upload successful');
}
I have an asset_category table(columns 'asset_category_id', 'category') and an asset table(columns 'asset_id', 'asset_category_id') and want display the (columns 'asset_id', 'asset_category_id.category,') from the asset table instead of just the 'asset_id' n 'asset_category_id' columns.
Asset_CatoriesController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Asset_category;
class Asset_CategoriesController extends Controller
{
public function asset_category(){
$asset_categories = Asset_category::all();
return view('category', ['asset_categories' => $asset_categories]);
}
public function add(Request $request){
$this->validate($request, [
'asset_category_id' => '',
'category' => 'required'
]);
$asset_categories = new Asset_category;
$asset_categories ->asset_category_id = $request->input('asset_category_id');
$asset_categories ->category = $request->input('category');
$asset_categories ->save();
return redirect('/category') ->with('info', 'New Category Saved Successfully!');
}
public function update($id){
$asset_categories = Asset_category::find($id);
return view('update', ['asset_categories' => $asset_categories]);
}
public function edit(Request $request, $id){
$this->validate($request, [
'asset_category_id' => '',
'category' => 'required'
]);
$data = array(
'category' => $request ->input('category')
);
Asset_category::where('asset_category_id', $id)->update($data);
return redirect('/category') ->with('info', 'Category Updated Successfully!');
}
public function delete($id){
Asset_category::where('asset_category_id', $id)
->delete();
return redirect('/category') ->with('info', 'Category Deleted Successfully!');
}
}
AssetController
<?php
namespace App\Http\Controllers;
use App\Asset;
use App\Asset_category;
use App\Manufacturer;
use App\Department;
use Illuminate\Http\Request;
class AssetController extends Controller
{
public function asset(){
$assets = Asset::all();
// return view::make('viewAsset')->with('assets', $assets);
return view('viewAsset', ['assets' => $assets]);
}
public function manufacturer(){
$manufacturers = Manufacturer::all();
return view('asset', ['manufacturers' => $manufacturers]);
}
public function add(Request $request){
$this->validate($request, [
'asset_id' => '',
'asset_category_id' => 'required',
'manufacturer_id' => 'required',
'department_id' => 'required',
]);
$assets = new Asset;
$assets ->asset_id = $request->input('asset_id');
$assets ->asset_category_id = $request->input('asset_category_id');
$assets ->manufacturer_id = $request->input('manufacturer_id');
$assets ->department_id = $request->input('department_id');
$assets ->save();
return redirect('/viewAsset') ->with('info', 'New Asset Saved Successfully!');
}
public function update($id){
$assets = Asset::find($id);
return view('updateAsset', ['assets' => $assets]);
}
public function edit(Request $request, $id){
$this->validate($request, [
'asset_id' => '',
'asset_category_id' => 'required',
'manufacturer_id'=> 'required',
'department_id' => 'required'
]);
$data = array(
'asset_category_id' => $request ->input('asset_category_id'),
'manufacturer_id' => $request ->input('manufacturer_id'),
'department_id' => $request ->input('department_id')
);
Asset::where('asset_id', $id)->update($data);
return redirect('/viewAsset') ->with('info', 'Asset Updated Successfully!');
}
public function delete($id){
Asset::where('asset_id', $id)
->delete();
return redirect('/viewAsset') ->with('info', 'Asset Deleted Successfully!');
}
}
Asset.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Asset_category;
class Asset extends Model
{
protected $primaryKey = 'asset_id';
public function category(){
return $this->belongsTo('Asset_category');
//$this->belongsTo('Asset_category');
//Asset_category::where('asset_category_id', $this->asset_category_id)->first()->category;
}
}
Asset_category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Asset;
class Asset_category extends Model
{
protected $primaryKey = 'asset_category_id';
public function asset() {
return $this->hasMany('Asset', 'asset_category_id');
}
}
viewAsset.php
#foreach($assets->all() as $asset)
<tr>
<td>{{ $asset->asset_id}}</td>
<td>{{ $asset->category->category}}</td>
when i run the project i get a FatalErrorExeception which says
Class 'Asset_category' not found in HasRelationships.php
You have Asset_category in a namespace. Try changing this:
return $this->belongsTo('Asset_category');
to this:
return $this->belongsTo(Asset_category::class);
You must end #foreach with #endforeach
You must declare protected $table = 'table_name'; in model because in default laravel generate table name to plural form of model's class name
Try to return this:
return $this->belongsTo('Asset_category');
return $this->hasMany('Asset', 'asset_category_id');
to this:
return $this->belongsTo(Asset_category::class);
return $this->hasMany(Asset::class, 'asset_category_id');