Data not getting inserted to db - laravel - php

I m try to insert data to db ! but function is working ok, it redirect to route assigned ! no error! but data is not getting added in db! I am not able to figure out ! anyhelp?
public function addfav($webmasterId,$id)
{
// Check Permissions
$data_sections_arr = explode(",", Auth::user()->permissionsGroup->data_sections);
if (Auth::user()->id =='1') {
return Redirect::to(route('NoPermission'))->send();
}
$dlt=DB::table('favads')->insertGetId([
['user_id' => Auth::user()->id, 'topic_id' => $id]
]);
//
// General for all pages
$GeneralWebmasterSections = WebmasterSection::where('status', '=', '1')->orderby('row_no', 'asc')->get();
// General END
//Webmaster Topic Details
$WebmasterSection = WebmasterSection::find($webmasterId);
if (!empty($WebmasterSection)) {
return redirect()->route('fav',['webmasterId'=>$webmasterId]);
} else {
return redirect()->route('NotFound');
}
}

Why are you having two [] ? Remove one of them, I think this is the problem
Change
$dlt=DB::table('favads')->insertGetId([
['user_id' => Auth::user()->id, 'topic_id' => $id]
]);
To
$dlt=DB::table('favads')->insertGetId(
['user_id' => Auth::user()->id, 'topic_id' => $id]
);
Check with try and catch, what error are you receiving
try{
$dlt=DB::table('favads')->insertGetId(
['user_id' => Auth::user()->id, 'topic_id' => $id]
);
dd($dlt);
}catch(\Exception $e){
dd($e->getMessage());
}

You have to use like this
$dlt = new Favad();
$dlt->user_id = Auth::user()->id;
$dlt->topic_id = $id;
$dlt->save();

Be sure that you are using the following code use App\Favad; in your controller.
You should insert data the following way:
$dlt = new Favad;
$dlt->user_id = Auth::user()->id;
$dlt->topic_id = $id;
$dlt->save();

Related

I can't change error message in my project

I have a Laravel 8 project. I want to change magic auth error message. And I did updated my code like this.
'This code has already been used' I replaced this message with this in the context of the code 'You will get a link in your email inbox every time you need to log in or register. Keep in mind that each link can only be used once.'
OLD AuthController.php
public function magicauth(Request $request)
{
$auth = app('firebase.auth');
$email = $request->email;
$oobCode = $request->oobCode;
$exits = User::where('email', $email)->first();
if(!is_null($exits))
{
if(is_null($exits->firebaseUserId))
{
$fUser = $auth->createUser([
'email' => $exits->email,
'emailVerified' => true,
'displayName' => $exits->name,
'password' => ($exits->email . $exits->id),
]);
$firebaseID = $fUser->uid;
$exits->update([
'firebaseUserId' => $firebaseID
]);
}
}
try
{
$result = $auth->signInWithEmailAndOobCode($email, $oobCode);
$firebaseID = $result->firebaseUserId();
$user = User::where('firebaseUserId', $firebaseID)->first();
if(is_null($user))
{
return view('auth.messages', ['message' => 'User not found']);
}
if($user->role_id != 3)
{
return view('auth.messages', ['message' => 'User is not creator']);
}
Auth::login($user);
return redirect()->route('home');
} catch (\Exception $e) {
return view('auth.messages', ['message' => 'This code has already been used.']);
}
return redirect()->route('login');
}
NEW AuthController.php
public function magicauth(Request $request)
{
$auth = app('firebase.auth');
$email = $request->email;
$oobCode = $request->oobCode;
$exits = User::where('email', $email)->first();
if(!is_null($exits))
{
if(is_null($exits->firebaseUserId))
{
$fUser = $auth->createUser([
'email' => $exits->email,
'emailVerified' => true,
'displayName' => $exits->name,
'password' => ($exits->email . $exits->id),
]);
$firebaseID = $fUser->uid;
$exits->update([
'firebaseUserId' => $firebaseID
]);
}
}
try
{
$result = $auth->signInWithEmailAndOobCode($email, $oobCode);
$firebaseID = $result->firebaseUserId();
$user = User::where('firebaseUserId', $firebaseID)->first();
if(is_null($user))
{
return view('auth.messages', ['message' => 'User not found']);
}
if($user->role_id != 3)
{
return view('auth.messages', ['message' => 'User is not creator']);
}
Auth::login($user);
return redirect()->route('home');
} catch (\Exception $e) {
return view('auth.messages', ['message' => 'You will get a link in your email inbox every time you need to log in or register. Keep in mind that each link can only be used once.']);
}
return redirect()->route('login');
}
But when I try now, I see that the message has not changed. How can I fix this?
Please follow below steps:
If you haven't done it yet, delete or rename the old AuthController class, use only new one, with new message.
Make sure routes going to the methods in the new controller
Run composer dump-autoload.
If the problem still persist I'd check whether some kind of cache mechanism is enabled in php, like opcache.

How I can access data property from MySQL in Controller

I learning about laravel framework, I don't know how to access property in my controller.
public function uuid(Request $request)
{
if($request->get('uuid') == null) return abort(404);
$uuid = $request->get('uuid');
$users = DB::table('users')->select('*')->where('uuid', $uuid)->get();
$result = array([
'id' => $users['id'],
'username' => $users['username'],
'uuid' => $users['uuid'],
]);
return view ('dashboard')->with('username', $result['username']);
}
in my dashboard.blade.php
{{$username}}
When i come to dashboard it show error like this
ErrorException (E_NOTICE)
Undefined index: username
Use First() instead of get() you'll get object so access data like.
$users = DB::table('users')->select('*')->where('uuid', $uuid)->first();
$result = array([
'id' => $users->id,
'username' => $users->username,
'uuid' => $users->uuid,
]);
return view ('dashboard')->with('username', $result['username']);
Now sort way to do it.
$user = DB::table('users')->select('*')->where('uuid', $uuid)->first();
$username = '';
if(!empty($user)){
$username = $user->username
}
return view ('dashboard',compact('username'));
$users is a collection of users. So you cannot access a property of a user like $users['id'];
If you want to get one user object from the database, you need to call first() instead of get()
Possible Solution
$user = DB::table('users')->select('*')->where('uuid', $uuid)->first();
You can use firstOrFail();
$users = DB::table('users')->select('*')->where('uuid', $uuid)->firstOrFail();
$result = array([
'id' => $users->id,
'username' => $users->username,
'uuid' => $users->uuid,
]);
return view ('dashboard')->with('username', compact('username'));
A possible short version of your solution may be like following
public function uuid(Request $request)
{
$user = User::select('username')->where('uuid', $request->uuid)->firstOrFail();
return view ('dashboard')->with('username', $user->username);
}

Laravel Property does not exist on this collection instance

I need to transfer data from Mysq table (Paniers) to another Mysql table (Commandes) and delete the data from first table after transfer.
Here is my code:
function Commande(Request $request) {
$pn = $request->input('id');
$pdr = Panier::find($pn);
$user = Commande::create([
'ID_User' => $pdr->ID_User,
'ID_Piece' => $pdr->ID_Piece,
'QTE' => $pdr->QTE,
]);
if($user){
if($pdr->delete())
{
echo 'Commande Confirmée';
}
}
}
I get this error:
"Property [ID_User] does not exist on this collection instance."
If i do this it works but instead of getting all data i only get the first line. I need to get all lines of data!
$pdr = Panier::find($pn)->first();
If $pn is array Panier::find($pn) returns collection not entity so you should iterate it
Panier::find($pn)->each(function($pdr){
$user = Commande::create([
'ID_User' => $pdr->ID_User,
'ID_Piece' => $pdr->ID_Piece,
'QTE' => $pdr->QTE,
]);
if($user){
if($pdr->delete())
{
echo 'Commande Confirmée';
}
}
});
When you are doing :
$pdr = Panier::find($pn);
If the record does not exist, it will return null. Then if you do $pdr->ID_User it is going to throw an error. Please check beloew updates :
<?php
function Commande(Request $request) {
$pn = $request->input('id');
$pdr = Panier::find($pn);
// Model not found
if(!$pdr){
return response()->json(['msg' => 'No records found']);
}
// Create new Commande
$user = Commande::create([
'ID_User' => $pdr->ID_User ?? 'default_value_for_ID_User',
'ID_Piece' => $pdr->ID_Piece ?? 'default_value_for_ID_Piece',
'QTE' => $pdr->QTE ?? 'default_value_for_QTE'
]);
// If user is created
if($user){
// Delete Panier
$pdr->delete();
return response()->json(['msg' => 'Success']);
}
return response()->json(['msg' => 'Could not create new Commande']);
}
For above to work you need to have :
Columns ID_User, ID_Piece and QTE marked as $fillable = [] in Commande Model.
You need to have a basic primary key for Panier Model, otherwise delete() will not work.
You can do it by findOrFail and handling Exception:
function Commande(Request $request) {
$pn = (int) $request->input('id');
try {
$pdr = Panier::findOrFail($pn);
$pdr->each(function ($item, $key) {
$user = Commande::create([
'ID_User' => $item->ID_User,
'ID_Piece' => $item->ID_Piece,
'QTE' => $item->QTE,
]);
if ($user && $item->delete()) {
echo 'Commande Confirmée';
}
});
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
//#Todo handle error
}
}
According to laravel 5.0 documents:
Retrieving A Model By Primary Key Or Throw An Exception
Sometimes you may wish to throw an exception if a model is not found. To do this, you may use the firstOrFail method:
Collection

Why do the values in my model not update in the database?

I am going to insert and update values using my addpermission function in my Controller
public function addPermission(Request $request, $id, $permission = null)
{
$this->validate($request, [
'status' => 'required'
]);
if(is_null($permission)) {
$permission = new Permission;
$msg = 'Permission has been added to your Collaborator successfully';
} else {
$permission = Permission::findOrFail($permission,['id'])->id;
$msg = 'Permission updated successfully';
}
$permission->status = $request->input('status');
$permission->project_id = $id;
$permission->collaborator_id = $request->input('cid');
$permission->save();
return redirect()->back()->with('info', $msg);
}
My routes
Route::post('projects/{project_id}/permission', [
'uses' => 'ProjectCollaboratorsController#addPermission',
'as' => 'projects.collaborators.permission',
// 'middleware' => ['auth']
]);
Data insert works properly, but update doesn't work.
When I click button to update it is inserts as new record to the database.
My table name is permission and have the following columns
id (autoincrement)
status
project_id
collaborator_id
What do I need to change to make the updating work?
I see an error in this line, this should return the permission object not the id of permission.
$permission = Permission::findOrFail($permission,['id'])->id;
Change to,
$permission = Permission::findOrFail($permission['id']);
You should write this. Hopefully This will solve your problem
public function addPermission(Request $request, $id, $permission)
{
$this->validate($request, [
'status' => 'required'
]);
$per = Permission::where('id', $permission)->first();
if(is_null($permission)) {
$permission = new Permission;
$msg = 'Permission has been added to your Collaborator successfully';
} else {
$permission = Permission::findOrFail($per)->id;
$msg = 'Permission updated successfully';
}
$permission->status = $request->input('status');
$permission->project_id = $id;
$permission->collaborator_id = $request->input('cid');
$permission->save();
return redirect()->back()->with('info', $msg);
}
I think you may need to put an optional route parameter in for permission id.
Route::post('projects/{project_id}/permission/{permission_id?}', [
'uses' => 'ProjectCollaboratorsController#addPermission',
'as' => 'projects.collaborators.permission',
// 'middleware' => ['auth']
]);

updating value in laravel using api call

I have been trying to update the handicap score using a post request. But I seem to get an error saying : creating default object from empty value.
Code :
public function handicap(Request $request)
{
$user = Auth::user();
$rules = array(
'handicap' => 'required'
);
$validator = Validator::make(Input::all(), $rules);
// process the login
if ($validator->fails())
{
return response()->json(['msg' => 'Failed to update Handicap score!'], 200);
}
else {
if(Handicap::where('user_id', '=', $user->id)->exists())
{
$handicap = Handicap::find($user->id);
$handicap->user_id = $user->id;
$handicap->handicap = $request->input('handicap');
$handicap->save();
return response()->json(['msg' => 'You have successfully updated your handicap score!'], 200);
}
else
{
$handicap = new Handicap;
$handicap->user_id = $user->id;
$handicap->handicap = $request->input('handicap');
$handicap->save();
return response()->json(['msg' => 'You have added your handicap score successfully!'], 200);
}
}
}
If user does not exist in Handicap table then the else block code runs and creates a handicap score for the user else the if block needs to execute and update the score. I tried many alternatives but dont seem to get it working. Dont know what am I doing wrong.
I checked the $user, $handicap variables using return. those variables have the info that I need to add to the table. Its just that Its not updating.
Your problem probably comes from the line you have Handicap::find($user->id). Obviously it's null, because such model was not found, even though your if statement returns true.
In your if statement you have where('user_id' , '=', $user->id), but you are using Handicap::find($user->id) which is basically Handicap::where('id', '=', $user->id)->first().
Try changing it to:
$handicap = Handicap::where('users_id', '=', $user->id)->first();
You may give this a try:
public function handicap(Request $request)
{
$validator = Validator::make(Input::all(), [
'handicap' => 'required'
]);
// process the login
if ($validator->fails()) {
return response()->json(['msg' => 'Failed to update Handicap score!'], 200);
}
$handicap = Handicap::firstOrNew([
'user_id' => $request->user()->id;
]);
$handicap->user_id = $request->user()->id;
$handicap->handicap = $request->handicap;
$handicap->save();
return response()->json(['msg' => 'You have successfully updated your handicap score!'], 200);
}

Categories