Laravel 5.4 : Property [id] does not exist on this collection instance - laravel

I have trouble saving image or fileupload in laravel 5.4.
the admin is the only one allowed to register a user together with his/her image upon registering the user should receive a confirmation email on his inbox. for other related codes that I think that is related to this controller and the email function or method that could have messed up my code.
paste bin https://pastebin.com/h3Sj7sGN?
//UserController
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Mail;
use App\Mail\verifyEmail;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$users = User::all();
//Load all users on the table and pass the users
$users = User::where(['archive'=>1])->orderBy('id')->get();
return view('usercrud.index')->with('users', $users);
}
public function create(Request $request)
{
//
if ($request->file('images') == null)
{
$file = "";
}else{
$filename = $request->images->getClientOriginalName();
$filesize = $request->images->getClientSize();
$file = $request->file('images')->storeAs('images', $filename);
$usersSt = new User;
$usersSt->filename = $filename;
$usersSt->filesize = $filesize;
$usersSt->position = $request->companyPos;
$usersSt->empid = $request->empid;
$usersSt->name = $request->fullname;
$usersSt->email = $request->email;
$usersSt->password = bcrypt($request->password);
$usersSt->roles = $request->role_id;
$usersSt->save();
}
$users = User::all();
$users = User::where(['archive'=>1])->orderBy('id')->get();
$thisUser = User::findOrFail($users->id);
$this->sendEmail($thisUser);
$thisUser = User::findOrFail($users->id);
dd($id);
$this->sendEmail($thisUser);
return redirect()->to('userIndex')->with('users', $users);
return $request->all();
}
public function verifyEmailFirst(Request $request)
{
//
return view('usercrud.verifyEmailFirst');
}
/* public function emailtoken(Request $request)
{
//
return
} */
/**
public function edit($id)
{
//
$users = User::where(['id'=>$id])->first();
// dd($users);
return view('usercrud.edit',compact('users'));
}
public function update(Request $request, $id)
{
//
$usersUp = new User;
$password = bcrypt($request->editpassword);
// dd($request->editcompanyPos);
$usersUp = User::where('id',$id)
->update(['position'=>$request->editcompanyPos,'name'=>$request-
>editfullname,'email'=>$request-
>editemail,'password'=>$password,'roles'=>$request->editrole_id]);
$users = User::all();
$users = User::where(['archive'=>1])->orderBy('id')->get();
return redirect()->to('userIndex')->with('users', $users);
}
public function destroy($id)
{
$userDel = User::where('id',$id)->update(['archive'=>0]);
$users = User::all();
$users = User::where(['archive'=>1])->orderBy('id')->get();
return redirect()->to('userIndex')->with('users', $users);
}
public function sendEmail($thisUser)
{
Mail::to($thisUser['email'])->send(new verifyEmail($thisUser));
}
public function sendEmailDone($email, $verifyToken)
{
$user = User::where(['email'=>$email, 'verifyToken'=>$verifyToken])-
>first();
//return $user;
if ($user){
return user::where(['email'=>$email, 'verifyToken'=>$verifyToken])-
>update(['status'=>'1','verifyToken'=>NULL]);
}else{
return 'user not found';
}
}
}

Do this
public function create(Request $request)
{
//
if ($request->file('images') == null)
{
$file = "";
}else{
$filename = $request->images->getClientOriginalName();
$filesize = $request->images->getClientSize();
$file = $request->file('images')->storeAs('images', $filename);
$usersSt = new User;
$usersSt->filename = $filename;
$usersSt->filesize = $filesize;
$usersSt->position = $request->companyPos;
$usersSt->empid = $request->empid;
$usersSt->name = $request->fullname;
$usersSt->email = $request->email;
$usersSt->password = bcrypt($request->password);
$usersSt->roles = $request->role_id;
$usersSt->save();
}
$this->sendEmail($usersSt);
return redirect()->to('userIndex')->with('users', $usersSt);
}

Related

How to add rule to User::create (laravel-8)

I want to add hashed password to a User::create($validation);
UserController
public function store_user(UserRoleStoreRequest $request){
$validated = $request->validated();
$password = Hash::make($validated["password"]);
$user = User::create($validated);
$roles = $validated['role_id'];
$user->roles()->sync($roles);
return redirect('/user-role');
}
Add this to the User model
public function setPasswordAttribute($value){
$this->attributes['password'] = bcrypt($value);
}

Fetch image as a url from mysql database in laravel Api

I want to fetch the image from database as a URL like http://127.0.0.1:8000/uploads/category/image.png
but the result I am getting is the name of the file not the URL.
This is the model class:
class CategoryModel extends Model
{
protected $table="tb_category";
public $timestamps = false;
protected $fillable = [
'id',
'name',
'image'
];
}
This is my controller class:
class CategoryController extends Controller
{
//
public function viewPage(){
return view('category');
}
public function saveCategory(Request $request){
$category = new CategoryModel();
$category->name=$request->input('name');
if($request->hasfile('image')){
$file=$request->file('image');
$extension = $file->getClientOriginalExtension();
$filename=time().'.'.$extension;
//$headers = array('Content-Type' => 'application/octet-stream');
$file->move('uploads/category/',$filename);
$category->image =$filename;
$category->_image =$filename;
}
else{
return $request;
$category->image='';
$category->_image=null;
}
$category->save();
return view('category')->with('category',$category);
}
public function getCategories(){
$res = CategoryModel::get(
['id','name','image'
]
);
return response()->json($res,200);
}
}
In your saveCategory method, you're storing $filename in 'image' column.
Change it to store path.
public function saveCategory(Request $request){
$category = new CategoryModel();
$category->name=$request->input('name');
if($request->hasfile('image')){
$file=$request->file('image');
$extension = $file->getClientOriginalExtension();
$filename=time().'.'.$extension;
$file->move('uploads/category/',$filename);
$category->image ='http://127.0.0.1:8000/uploads/category/'.$filename; //This is where you need to save absolute path of the image.
}
else{
return $request;
}
$category->save();
return view('category')->with('category',$category);
}
One more problem here is that you've written code after return $request; in else statement. Any code written after return is unreachable for the interpreter and will not be executed.

Too few arguments to function App\Http\Controllers\admin\ProductController::addToCart(), 2 passed and exactly 3 expected

Hello I am making a cart but when I click on add to cart link then it says: "Too few arguments to function App\Http\Controllers\admin\ProductController::addToCart(), 2 passed and exactly 3 expected", how can i sole this error error https://ibb.co/C2FZYD9
Thanks in advance,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}
routes:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request, $qty)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product, $qty);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
This is your route:
Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
and your function definition:
public function addToCart(Product $product, Request $request, $qty)
{
// ...
}
This function expects the $product and $qty to be passed through your route.
Too few arguments to function App\Http\Controllers\admin\ProductController::addToCart(), 2 passed and exactly 3 expected
This error means you only pass the product to the route.
Change the function definition or pass the parameter to the route and it will work.
Update
This is a small example, defining an option parameter to your addToCart function:
public function addToCart(Product $product, Request $request, $qty=0)
{
// ...
}
and for your route:
Route::get('/addToCart/{product}/{qty?}', 'Admin\ProductController#addToCart')->name('addToCart');
Hope it helps.
In your addToCart there are only two parameters passed so it searches for the third parameter in function addToCart. At mine this worked.
Route::get('/addToCart/{product}/{qty?}', 'Admin\ProductController#addToCart')->name('addToCart');

Correct way of updating, storing and deleting in many-to-many relationship in Laravel 5.6

I have this code and it's kinda working for storing and update but I don't know how to delete user's role by detach method. How can I delete a single role from multiple user's role? I am not sure about the codes along the roles()->attach() line which and I think you guys have a better solution to this.
UsersController:
public function store(Request $request)
{
if($request->isMethod('put'))
{
$user = User::findOrFail($request->id);
$user->name = $request->input('name');
$user->email = $request->input('email');
$role = Role::where('name',$request->input('role_id'))->first();
$user->roles()->attach($role->id);
}
else
{
$user = new User;
$user->name = $request->input('name');
$user->email = $request->input('email');
$user->password = Hash::make($request->input('password'));
$user->remember_token = str_random(40);
$user->id = User::count() + 1; //get the last user id? for pivot table
$user->roles()->attach(2); //default role (2) : admin is (1)
}
if($user->save()){
return response()->json($user);
}
}
User.php
public function roles(){
return $this->belongsToMany('App\Role');
}
Role.php
public function users(){
return $this->belongsToMany('App\User');
}
Pivot table
Schema::create('role_user', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
});
A method (not to say it is the right way) is to use the sync method (Syncing Associations).
I create a dropdown list in the form.
I have a function sat in a model that does the following;
public function selectListValues($key, $value, $where=[])
{
$list = [];
if (is_array($value)) {
array_unshift($value, $key);
$result = $this->model->where($where)->get($value);
foreach ($result->toArray() as $r) {
$index = $r[$key];
unset($r[$key]);
$list[$index] = implode(' ', $r);
}
} else {
try {
$result = $this->model->where($where)->get()->pluck($value, $key);
$list = $result->toArray();
} catch(ModelNotFoundException $e){
return null;
}
}
return $list;
}
which I call in the function that generates the form;
$roles = $roleModel->selectListValues('id', 'name');
then in my store method of the controller;
$roles = $request->get('roles');
$collection = new Collection();
foreach ($roles as $role) {
try {
$collection->add(Role::where('id', '=', $role)->firstOrFail());
} catch (\Exception $e) {
dd($e);
}
}
if (empty($collection)) {
throw new \Exception('No roles found for '.$user->email);
}
$user->roles()->sync($collection);

How to store data in a database using laravel

Please what is wrong with this code...am a newbie and this task was given to complete, I watch YouTube and read online but I can seem to figure out how to store records in database ...
This is UserController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Storage;
use App\User;
class UserController extends Controller {
/**
* #return $this
*/
public function showUsersWithProperty() {
$users = User::all()->filter(function($user) {
return $user->properties->count();
});
return view('settings.manageusers')
->with('users', $users);
}
public function editUser(Request $request, $id){
$users = User::all()->filter(function($user) {
return $user->properties->count();
});
$user = User::find($id);
return view('settings.manageusers')
->with('users', $users)->with('editId', $user->id);
}
public function updateUser(Request $request, $id){
$input = $request;
$user = User::find($input->id);
if ($input->hasFile('userPic')) {
$image = $input->file('userPic');
$realname = pathinfo($input->file('userPic')->getClientOriginalName(), PATHINFO_FILENAME);
$extension = $image->getClientOriginalExtension();
$new_name = time().".".$extension;
$image->storeAs('public/uploads', $new_name);
$path = Storage::url("uploads/" . $new_name);
$user->image_url = $path;
}
$user->first_name = $input->fname;
$user->last_name = $input->lname;
$user->pin = $input->changePin;
if($input->deactivate =="on" || $input->deleteUser =="on"){
$user->account_status = 0;
} else {
$user->account_status = 1;
}
$user->save();
return redirect()->route('manageUsers')->with('status', "User Updated");
} }
This my Route
Route::post('/settings/updateUser/',
'UserController#updateUser')->name("user.update");
Route::get('/settings/updateUser/',
'UserController#updateUser')->name("user.update");

Resources