codeigniter 4, update model - php

I connected my codeigniter app with mysql. I created a table model like that:
<?php namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model{
protected $table = 'I_user';
protected $allowedFields = ['email', 'password','active', 'hash'];
}
And now in my Controller, I want to update user by changing email for example. How to do that?
My controller:
<?php namespace App\Controllers;
use App\Models\UserModel;
class Confirm extends BaseController
{
public function index($email, $hash)
{
if(!isset($email) || !isset($hash)){
return redirect()->to('/');
}
$model = new UserModel();
$user = $model->where('email', $email)->first();
if($user['hash'] == $hash){
// update $user email..
??
}
}
}

You can do it in such way:
$model->where('email', $user['email'])->set(['email' => 'YourNewEmailAddress'])->update();
or
$model->update(['email'=> $user['email']], ['email' => 'YourNewEmailAddress']);

You could use update directly to the model data
$data = [
'email' => 'Yourupdatedemailhere'
];
$model->update($user['email'], $data);

If the Primary key is not "id" in your data-table, then you need to mention that in your Model.
protected $primaryKey = 'email';
Then use:
$model->update(['email'=> $user['email']], ['email' => 'newemail#example.com']);

Related

How to obtain three level model data laravel

Updated
User model
class User extends Authenticatable
{
use HasFactory, Notifiable, HasApiTokens, HasRoles;
const MALE = 'male';
const FEMALE = 'female';
protected $guard_name = 'sanctum';
public function educationalBackgrounds()
{
return $this->hasMany("App\Models\Users\EducationalBackground", "user_id");
}
public function seminars()
{
return $this->hasMany("App\Models\Users\Seminar", "user_id");
}
}
I have child table EducationalBackground which is related to User table
class EducationalBackground extends Model
{
use HasFactory;
protected $table = 'users.educational_backgrounds';
protected $fillable = [
'user_id',
'studies_type',
'year',
'course',
];
public function user()
{
return $this->belongsTo('App\Models\User', 'user_id');
}
public function educationalAwards()
{
return $this->hasMany("App\Models\Users\EducationalAward", "educational_background_id");
}
}
And a third table that i want to access the award field
class EducationalAward extends Model
{
use HasFactory;
protected $table = 'users.educational_awards';
protected $fillable = [
'educational_background_id',
'award',
'photo',
];
public function educationalBackground()
{
return $this->belongsTo('App\Models\Users\EducationalBackground', 'educational_background_id');
}
}
I have api get route here
Route::get('/educational-background/{id}', [UserProfileController::class, 'getEducationalBackground']);
Here is my api method it works fine. But i want to go deeper and access the data of third table.
public function getEducationalBackground($id)
{
$educationalBackground = EducationalBackground::with('user')->where('user_id', $id)->get();
return response()->json($educationalBackground, 200);
}
It looks like you're not really grasping the concept of relations yet. Also, I'd advise you to look into route model binding :) What you basically want to be doing is:
public function getEducationalBackground($id)
{
$user = User::find($id);
return $user->educationalBackgrounds()->with('educationalAwards')->get();
}
Also, when you're pretty sure that whenever you want to use backgrounds, you also want to use the awards, you can add the with(...) to the model definition like so:
class EducationalBackground extends Model
{
...
protected $with = ['educationalAwards'];
}
That way, you can simplify your controller method to:
public function getEducationalBackground($id)
{
$user = User::find($id);
return $user->educationalBackgrounds;
}

How to alias table in Laravel using newQuery()

I have a table with the name cotacaoitensfranqueado and I'd like to call it using just cif, I know I can do this DB::table('cotacaoitensfranqueado as cif') how I saw in this question, but I'd like to do that using my model.
$user = Auth::user();
$model_cotacaoitensfranqueado = new Cotacaoitensfranqueado();
$query = $model_cotacaoitensfranqueado->newQuery();
$query->select('cotacaoitensfranqueado.*', 'c.status');
$query->join('cotacao as c', [
['c.codigoconcentrador', 'cotacaoitensfranqueado.codigoconcentrador'],
['c.codigoempresa', 'cotacaoitensfranqueado.codigoempresa'],
['c.codigocotacao', 'cotacaoitensfranqueado.codigocotacao'],
]);
$query->where('cotacaoitensfranqueado.codigoconcentrador', (int)$user->codigoconcentrador)
->where('cotacaoitensfranqueado.codigoempresa', (int)$codigoempresa)
->where('cotacaoitensfranqueado.codigofilial', $user->codigofilial)
->where('cotacaoitensfranqueado.codigocotacao', (int)$codigocotacao)
->where('c.status', 'A');
$cotacao = $query->get();
You don't need to use newQuery() or (int) with Eloquent:
Cotacaoitensfranqueado::where('codigoconcentrador', auth()->user()->codigoconcentrador)->get();
But if you really want to use it, use query() instead because newQuery() is deprecated.
I realize how to solve the problem, you can do the alias in the model
Cotacaoitensfranqueado.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cotacaoitensfranqueado extends Model
{
protected $table = 'cotacaoitensfranqueado as cif';
public $timestamps = false;
}
Controller/CotacaoController.php
...
use App\Cotacaoitensfranqueado;
class CotacaoController extends Controller
{
...
public function canSendBuy($codigoempresa, $codigocotacao){
$user = Auth::user();
$model_cotacaoitensfranqueado = new Cotacaoitensfranqueado();
$query = $model_cotacaoitensfranqueado->query();
$query->select('cif.*', 'c.status');
$query->join('cotacao as c', [
['c.codigoconcentrador', 'cif.codigoconcentrador'],
['c.codigoempresa', 'cif.codigoempresa'],
['c.codigocotacao', 'cif.codigocotacao'],
]);
$query->where('cif.codigoconcentrador', (int)$user->codigoconcentrador)
->where('cif.codigoempresa', (int)$codigoempresa)
->where('cif.codigofilial', $user->codigofilial)
->where('cif.codigocotacao', (int)$codigocotacao)
->where('c.status', 'A');
$cotacao = $query->get();
dd($cotacao);
}
...
}

Laravel not picking up my table columns? - Laravel 5.5

i'm trying to retrieve a column from my database with laravel.. i've confirmed the column actually exists but apparently laravel doesn't think the same.. any help? thanks!
The error is the following..
"Property [Salt] does not exist on this collection instance."
accounts model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class accounts extends Authenticatable
{
protected $table = "accounts";
public $pkey = 'id';
protected $salt = 'Salt';
protected $fillable = ['id', 'Username', 'Key'];
public $timestamps = false;
}
CustomAuthController.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use Auth;
class CustomAuthController extends Controller
{
//Login
public function showLoginForm()
{
return view('auth.login');
}
public function login(Request $request)
{
$this->validate($request, [
'username' => 'required|max:255',
'Key' => 'required|max:255',
]);
$user= User::where('Username', '=', $request->username)->get();
$hashedpw = hash('whirlpool', $request->Key);
if(Auth::attempt(['Username' => $request->username, 'Key' => $request->Key]))
{
return 'Logged in successfully';
}
else
{
return 'error'. $request->username. ' '. $user->Salt; #problematic variable <-
}
}
}
Thanks!
Jack
Hi, Again.. I've narrowed down the problem although i cant figure out how to fix it.. If my account isn't logged in on my website i cant seem to access the salt column. But, if i'm logged into the site i can select it?..
use first() instead of get() -
$user= User::where('Username', '=', $request->username)->first();
As mentioned in #Sohel0415 answer, your query returns collection not a single user model. You should use first() instead of get()
Also your salt property visibility identifier is protected, you should change this to public for access property from outside.
You have Salt defined as protected $salt
so try $user->salt;
and it should work fine.

Laravel: PDOException in Connection.php line 319: SQLSTATE[42S02]

During database update, I try to validate my inputs, but I get this error message every time (clicked on submit button):
PDOException in Connection.php line 319: SQLSTATE[42S02]: Base table
or view not found: 1146 Table 'app_db.user_id' doesn't exist
Without validation my update works on the user_details table.
UserDetailsController.php
<?php
namespace App\Http\Controllers;
use Session;
use App\UserDetails;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Redirect;
class UserDetailsController extends Controller
{
public function index()
{
$details = UserDetails::all()->where('user_id', \Auth::user()->id);
return \View::make('pages.personal_datas')
->with('details', $details);
}
public function update()
{
$details = UserDetails::where('user_id', \Auth::user()->id)->first();
$validator = UserDetails::validate(Input::all());
if($validator->fails())
{
$messages = $validator->messages();
return redirect()->action('UserDetailsController#index')
->withErrors($validator);
}
else
{
$details->email = Input::get('email');
$details->phone = Input::get('phone');
$details->country = Input::get('country');
$details->city = Input::get('city');
$details->address = Input::get('address');
$details->save();
Session::flash('message', 'Successfully updated!');
return redirect()->action('UserDetailsController#index');
}
}
}
UserDetails.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Validator;
class UserDetails extends Model
{
public $timestamps = false;
protected $guarded = [];
protected $primaryKey = 'user_id';
protected $table = 'user_details';
public static $rules = array(
'email' => 'email|unique:user_id|required',
'phone' => 'min:11|required',
'country' => 'min:4|required',
'city' => 'min:2|required',
'address' => 'min:4|required',
);
public static function validate($data)
{
return Validator::make($data, static::$rules);
}
}
UPDATE
Your issue lies with your validation of the user email
unique:user_id -> unique:user_details, user_id should be the proper rule format
full rule will read: 'email' => 'email|unique:user_details,user_id|required'
Your original validation rule is trying to query the user_id table, which doesn't exist.

Using Notification is Pivotal

I am trying to use the laravel 5.3 notification system. I have a many to many relationship on a couple of models. What I need to do is loop through all of the request data and send a notification to everyone appropriate. It seems that the notification methods won't work within a foreach loop. The error is:
BadMethodCallException in Builder.php line 2448:
Call to undefined method Illuminate\Database\Query\Builder::routeNotificationFor()
The code I am trying to figure out is:
public function storeHoursused(Request $request, Lessonhours $lessonhours)
{
$this->validate($request, [
'date_time' => 'required',
'numberofhours' => 'required|numeric',
'comments' => 'required|max:700'
]);
$hoursused = new Hoursused();
$hoursused->date_time = $request['date_time'];
$hoursused->numberofhours = $request['numberofhours'];
$hoursused->comments = $request['comments'];
$lessonhours->hoursused()->save($hoursused);
foreach($lessonhours->players as $player){
$player->users;
Notification::send($player, new HoursusedPosted($player->user));
//$lessonhours->player->notify(new HoursusedPosted($lessonhours->player->users));
}
return back()->with(['success' => 'Hours Used successfully added!']);
}
Is there a way to collect related data and pass to notification methods?
UPDATE:
The Players model looks like:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Collective\Html\Eloquent\FormAccessible;
use Illuminate\Notifications\Notification;
use Illuminate\Notifications\Notifiable;
use Carbon\Carbon;
class Players extends Model
{
public $table = "players";
protected $fillable = array('fname', 'lname', 'gender', 'birthdate');
public function users()
{
return $this->belongsTo('App\User', 'users_id');
}
public function lessonhours()
{
return $this->belongsToMany('App\Lessonhours', 'lessonhour_player', 'players_id', 'lessonhours_id')
->withTimestamps();
}
public function getFullName($id)
{
return ucfirst($this->fname ) . ' ' . ucfirst($this->lname);
}
protected $dates = ['birthdate'];
protected $touches = ['lessonhours'];
public function setBirthdateAttribute($value)
{
$this->attributes['birthdate'] = Carbon::createFromFormat('m/d/Y', $value);
}
}
Your $player model needs to use the Illuminate\Notifications\Notifiable trait.

Categories