I am working in Laravel, and I have a model Group where I have rules for validation. I am attempting to have a unique name_group but only for the given year. The code below works perfectly if I replace .$this->year_groups with 2016 for example. But when I try to add the actual year of the group to be created by concatenating .this->year_groups, I get a syntax error:
Symfony \ Component \ Debug \ Exception \ FatalErrorException syntax error, unexpected '.', expecting ')'
I have looked at many examples and they (seem) to be written this way, and I just can't find what is wrong. I am thinking perhaps it has something to do that this is in an array...?
Any help would be greatly appreciated!!
Model:
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Group extends Eloquent implements UserInterface,RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'groups';
protected $primaryKey = "id_groups";
protected $fillable = array('name_groups','year_groups','grados_id_grados');
//The error is in the following $rules
public static $rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,' . $this->year_groups,
'grados_id_grados' => 'required'
);
public function grado()
{
return $this->belongsTo('Grado','grados_id_grados');
}
public function students()
{
return $this->belongsToMany('Student','group_student','id_group','id_student')->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany('Teacher','group_subject_teacher','id_group','id_teacher')->withPivot('id_subject','year_groups')->withTimestamps();
}
}
In the Controller I call validation from the store method:
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Group::$rules);
if($validation->passes()){
$group = new Group;
$group->name_groups = Input::get('name_groups');
$group->year_groups = Input::get('year_groups');
$group->grados_id_grados = Input::get('grados_id_grados');
$group->save();
}
}
Looking your code, it seems $rules is variable or property of class. The way you are assigning values to property are wrong, so it is throwing error. Look below code and arrange your code accordingly:-
class anyClass {
private $year_groups = "2016";
public $rules = [];
public function __construct(){
$this->rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,'.$this->year_groups,
'grados_id_grados' => 'required'
);
}
}
I changed Model to:
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Group extends Eloquent implements UserInterface,RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'groups';
protected $primaryKey = "id_groups";
protected $fillable = array('name_groups','year_groups','grados_id_grados');
//This part I changed
public static $rules = [];
public static function _construct($year){
$rules = array(
'year_groups'=> 'required',
'name_groups'=> 'required|unique:groups,name_groups,NULL, id_groups,year_groups,' . $year,
'grados_id_grados' => 'required'
);
return $rules;
}
public function grado()
{
return $this->belongsTo('Grado','grados_id_grados');
}
public function students()
{
return $this->belongsToMany('Student','group_student','id_group','id_student')->withTimestamps();
}
public function teachers()
{
return $this->belongsToMany('Teacher','group_subject_teacher','id_group','id_teacher')->withPivot('id_subject','year_groups')->withTimestamps();
}
}
Then in Controller:
public function store()
{
$input = Input::all();
$validation = Validator::make($input, Group::_construct(Input::get('year_groups')));
if($validation->passes()){
$group = new Group;
$group->name_groups = Input::get('name_groups');
$group->year_groups = Input::get('year_groups');
$group->grados_id_grados = Input::get('grados_id_grados');
$group->save();
}
}
Related
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;
}
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.
I'm trying to build a query from a Repository in a Model with 2 where clauses.
This is the data I have in a MySql table:
id name environment_hash
1 online_debit abc
2 credit_cart abc
I want to query by name and environment_hash. To do this, I created the method findByHashAndMethod() (see below).
But when I use it in my controller, like this:
$online_debit = $this->ecommercePaymentMethodRepository->findByHashAndMethod($hash, 'online_debit')->first();
or this:
$credit_card = $this->ecommercePaymentMethodRepository->findByHashAndMethod($hash, 'credit_cart')->first();
I keep getting both rows and not only the ones filtered. What's wrong with the code?
This is my PaymentMethodRepository.php
class EcommercePaymentMethodRepository extends BaseRepository
{
public function findByHashAndMethod($hash = null, $payment_method)
{
$model = $this->model;
if($hash)
{
$filters = ['environment_hash' => $hash, 'name' => $payment_method];
$this->model->where($filters);
}
else
{
$this->model->where('environment_hash', Auth::user()->environment_hash)
->where('name', $payment_method);
}
return $model;
}
public function model()
{
return EcommercePaymentMethod::class;
}
}
And this is my model EcommercePaymentMethod.php
<?php
namespace App\Models;
use Eloquent as Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class EcommercePaymentMethod extends Model
{
use SoftDeletes;
public $table = "ecommerce_payment_methods";
protected $dates = ['deleted_at'];
public $fillable = [
"name",
"payment_processor_id",
"active",
"environment_hash"
];
protected $casts = [
"name" => "string"
];
public function payment_processor()
{
return $this->hasOne('App\Models\EcommercePaymentProcessor');
}
}
While I am not entirely sure why ->first() would ever return more than one result, your Repository method had some few glaring issues that's prone to errors.
class EcommercePaymentMethodRepository extends BaseRepository
{
// 1. Do not put optional parameter BEFORE non-optional
public function findByHashAndMethod($payment_method, $hash = null)
{
// 2. Call ->model() method
$model = new $this->model();
// 3. Logic cleanup
if (is_null($hash)) {
$hash = Auth::user()->environment_hash;
}
return $model->where('environment_hash', $hash)
->where('name', $payment_method);
}
public function model()
{
return EcommercePaymentMethod::class;
}
}
I try to update the laravel with php excel while installing i found the below warning in the composer.
Error:
Warning: Ambiguous class resolution, "SettingsController" was found in both
"C:\xampp\htdocs\mti\app\controllers\SettingsController.php" and
"C:\xampp\htdocs\mti\app\controllers\SettingsControllerBackup.php", the first
will be used.Warning: Ambiguous class resolution, "ClassModel" was found in both
"C:\xampp\htdocs\mti\app\models\ClassModel.php" and "C:\xampp\htdocs\mti\
app\models\LoginModel.php", the first will be used.
SettingsController:
<?php
class SettingsController extends BaseController
{
public function ChangePasswordLayout()
{
return View::make('settings/changepassword/changepassword');
}
public function ChangePasswordProcess()
{
$PasswordData = Input::all();
Validator::extend('pwdvalidation', function($field, $value, $parameters)
{
return Hash::check($value, Auth::user()->password);
});
$messages = array('pwdvalidation' => 'The Old Password is Incorrect');
$validator = Validator::make($PasswordData, User::$rulespwd, $messages);
if ($validator->passes())
{
$user = User::find(Auth::user()->id);
$user->password = Hash::make(Input::get('NewPassword'));
$user->save();
return Redirect::to('changepassword')->withInput()->with('Messages', 'The Password Information was Updated');
} else
{
return Redirect::to('changepassword')->withInput()->withErrors($validator);
}
}
public function ProfileLayout()
{
$user = Auth::user()->id;
$ProfileDetailsbyid = ProfileModel::where('id', $user)->get()->toArray();
return View::make('settings/profile/profile')->with('ProfileDetailsbyid', $ProfileDetailsbyid);
}
public function ProfileUpdateProcess($data=NULL)
{
$user = Auth::user()->id;
$ProfileDetailsbyid = ProfileModel::where('id', $user)->get()->toArray();
$ProfileData = array_filter(Input::except(array('_token')));
$validation = Validator::make($ProfileData, ProfileModel::$rules);
if ($validation->passes())
{
if(!empty($ProfileData['Photo']))
{
Input::file('Photo')->move('assets/uploads/profilephoto/', $user . '-Photo.' . Input::file('Photo')->getClientOriginalName());
$Photo=$user.'-Photo.' . Input::file('Photo')->getClientOriginalName();
unset($ProfileData['Photo']);
$ProfileData['Photo']=$Photo;
}
$affectedRows = ProfileModel::where('id', $user)->update($ProfileData);
//VehicleModel::create($VehicleData);
return Redirect::to('profile')->with('Message', 'Profile Details Update Succesfully')->with('ProfileDetailsbyid', $ProfileDetailsbyid);
} else
{
return Redirect::to('profile')->withInput()->withErrors($validation->messages())->with('ProfileDetailsbyid', $ProfileDetailsbyid);
}
}
}
ClassModel:
<?php
class ClassModel extends Eloquent
{
protected $primaryKey = 'AutoID';
protected $created_at = 'CreatedAt';
protected $updated_at = 'UpdatedAt';
protected $table = 'class';
protected $guarded = array('GradeName');
protected $fillable = array('GradeName');
public function batch(){
return $this->hasMany('BatchModel', 'Class');
}
public function studentadmissionresult(){
return $this->hasMany('StudentAdmissionModel', 'StudentCourse');
}
public $timestamps = true;
public static $rules = array(
'GradeName' => array('required', 'unique:class','regex:/^./'),
'GradeSection' => 'required',
'GradeCode' => array('required', 'unique:class')
);
public static $updaterules = array(
'GradeName' => array('required','regex:/^./'),
'GradeSection' => 'required',
'GradeCode' => array('required')
);
}
I following this tutorial:
https://github.com/Maatwebsite/Laravel-Excel
I have try following command :
composer require maatwebsite/excel": "~1.2.1
This actually has nothing to do with the package you are installing.
Explanation
When recreating the autoload files (composer dump-autoload) after the update Composer detected that you have two classes with the exact same name (but in different files).
Class SettingsController in SettingsController.php and SettingsControllerBackup.php
and class ClassModel in ClassModel.php and LoginModel.php
Composer will then choose to use one of the two (I'm not sure how it makes that decision, it's probably just the first one it finds) and will ignore the other occurrence. - Confirmed. Composer uses first match.
Solutions
Delete the files if you don't need them
Rename the class
A good and common practice is to name the class like the file. This is a simple way to avoid such collisions because two files in the same directory can't have the same name.
I created the model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class ClientModel extends Eloquent implements UserInterface, RemindableInterface {
protected $connection = 'local_db';
protected $table = 'administrators';
protected $fillable = ['user_id'];
public function getAuthIdentifier()
{
return $this->username;
}
public function getAuthPassword()
{
return $this->password;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function getReminderEmail()
{
return $this->email;
}
}
When I try to use it like this:
ClientModel::create(array(
'username' => 'first_user',
'password' => Hash::make('123456'),
'email' => 'my#email.com'
));
It creates empty entry in DB...
I think you make it too complicated. There is no need to make it this way. By default you have User model created and you should be able simple to create user this way:
$user = new User();
$user->username = 'something';
$user->password = Hash::make('userpassword');
$user->email = 'useremail#something.com';
$user->save();
Maybe you wanted to achieve something more but I don't understand what you use so many methods here if you don't modify input or output here.
You are using create method (Mass Assignment) so it's not working because you have this:
// Only user_id is allowed to insert by create method
protected $fillable = ['user_id'];
Put this in your model instead of $fillable:
// Allow any field to be inserted
protected $guarded = [];
Also you may use the alternative:
protected $fillable = ['username', 'password', 'email'];
Read more about Mass Assignment on Laravel website. While this may solve the issue but be aware of it. You may use this approach instead:
$user = new User;
$user->username = 'jhondoe';
// Set other fields ...
$user->save();
Nowadays way :
User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
or even:
$arrLcl = [];
$arrLcl['name'] = $data['name'];
$arrLcl['email'] = $data['email'];
$arrLcl['password'] = $data['password'];
User::create($arrLcl);