How to store data in a database using laravel - 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");

Related

Adding key-value to Laravel result object/collection

New to Laravel. Have what seems like should be a non-issue, but is causing a headache.
I'm trying to insert a key-value pair (bookingRef) within the result object/collection returned, such that the result would be:
[{"class_id":7,"class_name":"beginner","class_slots_avail":100,"class_slots_booked":53,"class_date":"2020-12-07 21:47:23","class_time":"09:25:00","class_reg_price":350, bookingRef: 127}]
I've tried methods such as push, put and merge that will insert the key-value after the object returned, but this is not what I require.
Here is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Booking;
use App\Http\Controllers\Auth;
use Illuminate\Support\Facades\Mail;
use DB;
class BookingsController extends Controller
{
//
function store(Request $request) {
$id = $request->input('class');
if(DB::table('classes')->where('class_id', '=', $id)->exists()) {
if(DB::table('classes')->where('class_id', '=', $id)->value('class_slots_booked')
< DB::table('classes')->where('class_id', '=', $id)->value('class_slots_avail')) {
$booking = new Booking();
$booking->class_id = $id;
$booking->user_id = \Auth::id();
$booking->save();
DB::table('classes')->where('class_id', '=', $id)->increment('class_slots_booked', 1);
if($booking) {
$confBook = DB::table('classes')->where('class_id', '=', $id)->get();
$confBook->bookingRef = $booking->id;
\error_log($confBook);
}
}
else return('CLASS FULLY BOOOOKED');
}
else return('CLASS NOT Available');
}
}
You can cut down on your queries and put this extra data in place with some adjustments:
function store(Request $request)
{
$id = $rquest->input('class');
$class = DB::table('classes')->where('class_id', $id)->first();
if ($class) {
if ($class->class_slots_booked < $class->class_slots_avail) {
$booking = new Booking();
$booking->class_id = $id;
$booking->user_id = $request->auth()->id;
if ($booking->save()) {
// adding the extra data
$class->bookingRef = $booking->id;
DB::table('classes')->where('class_id', $id)
->increment('class_slots_booked', 1);
$class->class_slots_booked++;
return view('view-booking', [
'bookings' => collect($class),
]);
}
// booking did not save
}
// unavailable
}
// class not found
}
This would be a little more convenient with a Model for the classes table and a relationship setup to Booking would be a plus as well.
I managed to resolve it, thanks to Lagbox's suggestion of using a model:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Booking;
use App\Models\Classes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
class BookingsController extends Controller
{
//
function store(Request $request) {
$id = $request->input('class');
$class = Classes::where('class_id', $id)->first();
if($class) {
if($class->class_slots_booked < $class->class_slots_avail) {
$booking = new Booking();
$booking->class_id = $id;
$booking->user_id = Auth::id();
if($booking->save()){
$class->where('class_id', $id)->increment('class_slots_booked');
$class->bookingRef = $booking->id;
return view('view-booking', ['bookings' => $class]);
}
}
else return('Class Fully Booked');
}
else return('Class Not Available');
}
};
From what I can see, the get() method returns an array with object(s), which is why object->new_property = value would not work. The first() method, however, seems to return a single object, which is why it would.
Seems I've got some reading up on models and collections to do.

Larave 6 l “Creating default object from empty value”

Here, I have setuo CRUD table with laravel, vuetify and vue . I could successfull create and read data from the database. But, for some reason my update and delete are not working. I am getting error like:
{message: "Creating default object from empty value", exception: "ErrorException",…}
exception: "ErrorException"
file: "C:\WinNMP\WWW\chillibiz\app\Sys\Http\Controllers\StageController.php"
line: 53
message: "Creating default object from empty value"
trace: [{file: "C:\WinNMP\WWW\chillibiz\app\Sys\Http\Controllers\StageController.php", line: 53,…},…]
My code are here:
StageController.php
<?php
namespace App\Sys\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Sys\Model\Stage;
class StageController extends Controller
{
public function index(Request $request)
{
$per_page = $request->per_page ? $request->per_page : 5;
$sort_by = $request->sort_by;
$order_by = $request->order_by;
return response()->json(['stages' => Stage::orderBy($sort_by, $order_by)->paginate($per_page)],200);
}
public function store(Request $request)
{
$uuid = Str::uuid()->toString();
$stage= Stage::create([
'id' => $uuid,
'code' =>$request->code,
'name' =>$request->name,
'description' =>$request->description,
]);
return response()->json(['stage'=>$stage],200);
}
public function show($id)
{
$stages = Stage::where('code','LIKE', "%$id%")->orWhere('name','LIKE', "%$id%")->orWhere('description', 'LIKE', "%$id%")->paginate();
return response()->json(['stages' => $stages],200);
}
public function update(Request $request, $id)
{
$stage = Stage::find($id);
$stage->code = $request->code; //line 53
$stage->name = $request->name;
$stage->description = $request->description;
$stage->save();
return response()->json(['stage'=>$stage], 200);
}
public function destroy($id)
{
$stage = Stage::where('id', $id)->delete();
return response()->json(['stage'=> $stage],200);
}
public function deleteAll(Request $request){
Stage::whereIn('id', $request->stages)->delete();
return response()->json(['message', 'Records Deleted Successfully'], 200);
}
}
Stage.php
<?php
namespace App\Sys\Model;
use Illuminate\Database\Eloquent\Model;
class Stage extends Model
{
protected $guarded = [];
}
I just found they you are using uuid as id not increment. that why you get error like that:
to solve your problem you need to add the field to your model;
<?php
namespace App\Sys\Model;
use Illuminate\Database\Eloquent\Model;
class Stage extends Model
{
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
}
I hope this time you can solve your problem. happy coding.
Edit you can read docs for more info

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.

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

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);
}

Should I define model class functions for repeated controller codes in Laravel 5?

I use the code like that repeatedly in my controllers:
...
if (Cache::has('user_' . $id)) {
$user = Cache::get('user_' . $id);
} else {
$user = User::with('location')->find($id);
if(!$user) {
return Response::view('errors/404', array());
}
Cache::put('user_' . $id, $user, 15);
}
...
Is it best practice to place them in Model classes as a class function? So that I would write just one line:
$user = User::getUserDetails($id);
And in model classes:
public function getUserDetails($id)
{
if(Cache::has('user_' . $id)) {
$user = Cache::get('user_' . $id);
} else {
$user = User::with('location')->find($id);
if(!$user) {
return Response::view('errors/404', array());
}
Cache::put('user_' . $id, $user, 15);
}
return $user;
}
What do you suggest?
You have two options, either use Helpers or just put it in one controller.
You just need to set it as static function.
public static function getUserDetails($id)
{
if(Cache::has('user_' . $id)) {
$user = Cache::get('user_' . $id);
} else {
$user = User::with('location')->find($id);
if(!$user) {
return Response::view('errors/404', array());
}
Cache::put('user_' . $id, $user, 15);
}
return $user;
}
If you use Helpers.
use Helpers;
Helpers::getUserDetails($id);
If you use Controller.
use App\Http\Controllers\TheControllerName;
TheControllerName::getUserDetails($id)
You can make a repository for reusable code.
Make a repository in app/Repositories/UserRepository.php
<?php
namespace App\Repositories;
use App/User;
/**
* Class UserRepository
*
* #package App\Repositories
*/
class UserRepository
{
public static function getUserDetails($id)
{
if(Cache::has('user_' . $id)) {
$user = Cache::get('user_' . $id);
} else {
$user = User::with('location')->find($id);
if(!$user) {
return Response::view('errors/404', array());
}
Cache::put('user_' . $id, $user, 15);
}
return $user;
}
}
In your controller, You can use like this:
<?php
namespace App\Http\Controllers;
use App\Repositories\UserRepository;
class UserController extends Controller
{
protected $user_repo;
public function __construct(UserRepository $user)
{
..
$this->user_repo = $seo;
..
}
public function YourFunctionName()
{
..
$this->user_repo->getUserDetails($id);
..
}
}
Please let me know for any confusion!

Resources