The model works well. The controller works well. The only place I'm having an error is in the view.
class Course extends Model
{
use SoftDeletes, FilterByUser;
protected $fillable = ['title', 'description', 'course_image', 'start_date', 'active', 'mandatory', 'created_by_id'];
protected $hidden = [];
public static $searchable = [
'title',
'description',
];
public static function boot()
{
parent::boot();
Course::observe(new \App\Observers\UserActionsObserver);
}
/**
* Set attribute to date format
* #param $input
*/
public function setStartDateAttribute($input)
{
if ($input != null && $input != '') {
$this->attributes['start_date'] = Carbon::createFromFormat(config('app.date_format'), $input)->format('Y-m-d');
} else {
$this->attributes['start_date'] = null;
}
}
/**
* Get attribute from date format
* #param $input
*
* #return string
*/
public function getStartDateAttribute($input)
{
$zeroDate = str_replace(['Y', 'm', 'd'], ['0000', '00', '00'], config('app.date_format'));
if ($input != $zeroDate && $input != null) {
return Carbon::createFromFormat('Y-m-d', $input)->format(config('app.date_format'));
} else {
return '';
}
}
/**
* Set to null if empty
* #param $input
*/
public function setCreatedByIdAttribute($input)
{
$this->attributes['created_by_id'] = $input ? $input : null;
}
public function created_by()
{
return $this->belongsTo(User::class, 'created_by_id');
}
public function trainers()
{
return $this->belongsToMany(User::class, 'course_user');
}
public function lessons()
{
return $this->hasMany('\App\Lesson');
}
}
I seem to have an issue with pagination. Here is the code I have for the controller and that works well.
public function index()
{
$course =Course::paginate(15);
return view('admin.courses.learn', compact('course'));
}
Here is what I have for the view:
{{$course->links()}}
this is where I get an error Call to undefined method App\Course::link()
Does anyone know what I'm doing wrong?
The Controller Code :
public function index()
{
$course =Course::paginate(15);
return view('admin.courses.learn', compact('course'));
}
Here is for the view:
#foreach($course as $row)
//Whatever you wanted to display will be written here
#endforeach
{!! $course->render() !!}
OR
#foreach($course as $row)
//Whatever you wanted to display will be written here
#endforeach
{{$course->links()}
The Controller code is fine.
public function index()
{
$course =Course::paginate(15);
return view('admin.courses.learn', compact('course'));
}
Now let's take a look at view.
#foreach($course as $row)
//Whatever action you wanted to do will be written here
#endforeach
{{$course->links()}} //The name should be differ than the name we used inside the foreach loop.
Related
This Is My "Mark" Model. I have 3 model linked with this model.
use HasFactory;
protected $table = 'marks';
protected $fillable = [
'subject_id',
'student_id',
'exam_id',
'mark',
];
public function exams() {
return $this->belongsTo(Exam::class);
}
public function students() {
return $this->belongsTo(Student::class);
}
public function subjects() {
return $this->belongsTo(Subject::class);
}
This Is My Exam Model. this is linked with Mark model
use HasFactory;
protected $table = "exams";
protected $fillable = [
'exam',
];
public function marks() {
return $this->hasMany(Mark::class);
}
This Is My MarkController. This is my controller in which 3 model are linked
public function index()
{
$marks = Mark::all();
$students = Student::all();
$subjects = Subject::all();
$exams = Exam::all();
return view('marks.index', compact('marks', 'students', 'subjects', 'exams'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('marks.create');
}
This is my marks.create where error is occurring in line 20
<td>
<select name="exam_id" id="exam_id" class="form-control">
<option value="">Select One</option>
#foreach ($exams as $exam)
<option value="{{ $exam->id }}">{{ $exam->name }}</option>
#endforeach
</select>
</td>
You can do like this
public function index()
{
$marks = Mark::all();
$students = Student::all();
$subjects = Subject::all();
$exams = Exam::all();
return view('marks.index', compact('marks', 'students', 'subjects', 'exams'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$exams = Exam::all(); //this part is missing
return view('marks.create', compact('exams'));
}
I want to import some categories, but what i need is also the parent category id.
public function importCategory(Request $request, $cat_id){
$import = new CategoryImport($cat_id);
$import->import($request->file);
if ($import->failures()->count() > 0) {
$message = '';
foreach ($import->failures() as $failure) {
$failure->row(); // row that went wrong
$failure->attribute(); // either heading key (if using heading row concern) or column index
$failure->errors(); // Actual error messages from Laravel validator
$failure->values(); // The values of the row that has failed.
}
return redirect()->back();
} else {
return redirect()->back()->with('success', sprintf('Success'));
}
}
Here is the CategoryImport.php
class CategoryImport implements WithHeadingRow, WithValidation, SkipsOnFailure,OnEachRow
{
use Importable, SkipsFailures;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
protected $cat_id = null;
public function __construct( $cat_id) {
$category_id = $cat_id;
}
public function onRow(Row $row)
{
$row=$row->toArray();
Category::create([
'name' => $row['name'],
'image' => $row['image'],
'business_category_id' => $this->category_id,
]);
}
}
So here is the error, it says undefined property, and i am trying to figure it out but don't understand.
Undefined property: App\Imports\CategoryImport::$category_id
Inside the constructor you need to assign the correct variable.
class CategoryImport implements WithHeadingRow, WithValidation, SkipsOnFailure,OnEachRow
{
use Importable, SkipsFailures;
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
protected $cat_id = null;
public function __construct($cat_id) {
$this->cat_id = $cat_id;
}
I think the line 'business_category_id' => $this->category_id is wrong. You need to use
'business_category_id' => $this->cat_id
because that is the variable you assign in the constructor.
You didn't set cat_id properly. In your CategoryImport you should have :
protected $category_id = null;
public function __construct($cat_id) {
$$this->category_id = $cat_id;
}
I have done my coding but the laravel audit seems not catch the data for update.
The data i try to update is on the column of value, but on the database the value are not be catch on audit table for auditing the update changes .
below is the coding for update the data.
academicsetting.php:
class AcademicSetting extends Model implements Auditable
{
use SoftDeletes, ActiveScope;
use \OwenIt\Auditing\Auditable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $dates = ['deleted_at'];
protected $fillable = [
'id',
'type',
'field',
'name',
'value',
'description',
'is_active',
'created_by',
'created_at',
'updated_by',
'updated_at',
'deleted_by',
'deleted_at',
];
protected $casts = [
'value' => 'json',
];
public function transformAudit(array $data): array
{
dump($data);exit();
if ($data['event'] == 'created') {
$data['new_values']['created_by'] = Staff::where('id', $this->getAttribute('created_by'))->value('name');
$data['new_values']['updated_by'] = Staff::where('id', $this->getAttribute('updated_by'))->value('name');
}
if ($data['event'] == 'deleted') {
$data['old_values']['deleted_by'] = Staff::where('id', $this->getOriginal('deleted_by'))->value('name');
$data['new_values']['deleted_by'] = Staff::where('id', $this->getAttribute('deleted_by'))->value('name');
}
if ($data['event'] == 'updated') {
$data['old_values']['updated_by'] = Staff::where('id', $this->getOriginal('updated_by'))->value('name');
$data['new_values']['updated_by'] = Staff::where('id', $this->getAttribute('updated_by'))->value('name');
}
return $data;
}
}
academicgeneralcontroller.php:
public function update(Request $request, $id)
{
/** implode multi dropdown value */
$request['final_attendance_reset_mark'] = $request->input('final_attendance_reset_mark');
/** end */
$this->general->update($request->except('_token', 'academicsetting-table_length', '_method'), $id);
Session::flash('alert-success', msg('msg_success_update'));
return redirect()->route('academic_general.index');
}
generalrepository.php:
class GeneralRepository extends Repository
{
/**
* Specify Model class name
*
* #return mixed
*/
public function model()
{
return AcademicSetting::class;
}
public function update(array $data, $id, $attribute = 'id')
{
// dump($data);exit();
foreach ($data as $key => $value) {
if ($key == 'final_attendance_reset_mark') {
$array = [];
if (!empty($value)) {
foreach ($value as $key_value => $value) {
$array[(int) $key_value] = (int) $value;
}
}
$json = json_encode($array, JSON_FORCE_OBJECT);
// dump($json);
$update_value = [
'value' => $json,
];
} else {
$update_value = ['value' => $value];
}
dump($update_value);exit();
$general = AcademicSetting::where('field', $key)->update($update_value);
}
}
}
Not sure if this will help but,
i see you have the following in the transform method:
$data['new_values']['created_by'] = Staff::where('id', $this->getAttribute('created_by'))->value('name');
in the documentation i see the following:
$data['old_values']['role_name'] = Role::find($this->getOriginal('role_id'))->name;
the above is to record the audit by transforming the role_id to the role_name, enabling you to capture the role_name as well.
https://laravel-auditing.herokuapp.com/docs/4.1/audit-transformation
This is the error I am getting the at moment:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\BelongsToMany::save()
must be an instance of Illuminate\Database\Eloquent\Model,
integer given,
called in /home/sasha/Documents/OffProjects/vetnearme/vetnearme/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Relations/BelongsToMany.php on line 814
The create user method, where I call the giveRole() method:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
// On registration user will be given the default role of user
$user->giveRole();
$verifyUser = VerifyUser::create([
'user_id' => $user->id,
'token' => str_random(40)
]);
Mail::to($user->email)->send(new VerifyMail($user));
return $user;
}
HasPermissionsTrait:
<?php
namespace App\App\Permissions;
use App\{Role, Permission};
/**
*
*/
trait HasPermissionsTrait
{
public function giveRole($role = 'user')
{
$role = \DB::table('roles')->where('name', '=', $role)->first();
$this->roles()->saveMany([$role->id]);
return $this;
}
public function givePermission(...$permissions)
{
$permissions = $this->getPermissions(\array_flatten($permissions));
if($permissions === null)
return $this;
$this->permissions()->saveMany($permissions);
return $this;
}
public function widrawPermission(...$permissions)
{
$permissions = $this->getPermissions(\array_flatten($permissions));
$this->permissions()->detach($permissions);
return $this;
}
public function updatePermissions(...$permissions)
{
$this->permissions()->detach();
return $this->givePermission($permissions);
}
public function hasRole(...$roles)
{
foreach ($roles as $role) {
if($this->roles->contains('name', $role))
return true;
}
return false;
}
public function hasPermissionTo($permission)
{
return $this->hasPermissionThroughRole($permission) || $this->hasPermission($permission);
}
protected function hasPermission($permission)
{
return (bool) $this->permissions->where('name', $permission->name)->count();
}
protected function hasPermissionThroughRole($permission)
{
foreach ($permission->roles as $role) {
if($this->role->contains($role))
return true;
}
return false;
}
protected function getPermissions(array $permissions)
{
return Permissions::whereIn('name', $permissions)->get();
}
public function roles()
{
return $this->belongsToMany(Role::class, 'users_roles', 'user_id', 'role_id');
}
public function permissions()
{
return $this->belongsToMany(Permissions::class, 'users_permissions');
}
}
Role model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function permissions()
{
return $this->belongsToMany(Permissions::class, 'roles_permissions');
}
}
User model:
namespace App;
use App\App\Permissions\HasPermissionsTrait;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable, HasPermissionsTrait;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function clinic()
{
return $this->hasOne(Clinic::class, 'owner_id');
}
public function files()
{
return $this->hasMany('App/Media');
}
public function verifyUser()
{
return $this->hasOne('App\VerifyUser');
}
}
What am I doing wrong here?
Have you tried passing in the role model instead of the id? Also, on a separate note, it looks as if you might as well just call save as you are not actually ever utilizing an array in this instance.
trait HasPermissionsTrait
{
public function giveRole($role = 'user')
{
$role = \DB::table('roles')->where('name', '=', $role)->first();
$this->roles()->saveMany([$role]);
return $this;
}
}
saveMany calls save:
public function saveMany($models, array $joinings = [])
{
foreach ($models as $key => $model) {
$this->save($model, (array) Arr::get($joinings, $key), false);
}
$this->touchIfTouching();
return $models;
}
and save has typecasted Model, not int:
/**
* Save a new model and attach it to the parent model.
*
* #param \Illuminate\Database\Eloquent\Model $model
* #param array $joining
* #param bool $touch
* #return \Illuminate\Database\Eloquent\Model
*/
public function save(Model $model, array $joining = [], $touch = true)
{
$model->save(['touch' => false]);
$this->attach($model->getKey(), $joining, $touch);
return $model;
}
I am struggling to understand how laravel works and I have a very difficult time with it
Model - User.php the User model
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable = array('email' , 'username' , 'password', 'code');
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password');
public function Characters()
{
return $this->hasMany('Character');
}
/**
* Get the unique identifier for the user.
*
* #return mixed
*/
public function getAuthIdentifier()
{
return $this->getKey();
}
/**
* Get the password for the user.
*
* #return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the e-mail address where password reminders are sent.
*
* #return string
*/
public function getReminderEmail()
{
return $this->email;
}
}
Model - Character.php the character model
<?php
class Character extends Eloquent {
protected $table = 'characters';
protected $fillable = array('lord_id','char_name', 'char_dynasty', 'picture');
public function user()
{
return $this->belongsTo('User');
}
public function Titles()
{
return $this->hasMany('Title');
}
}
?>
routes.php
Route::group(array('prefix' => 'user'), function()
{
Route::get("/{user}", array(
'as' => 'user-profile',
'uses' => 'ProfileController#user'));
});
ProfileController.php
<?php
class ProfileController extends BaseController{
public function user($user) {
$user = User::where('username', '=', Session::get('theuser') );
$char = DB::table('characters')
->join('users', function($join)
{
$join->on('users.id', '=', 'characters.user_id')
->where('characters.id', '=', 'characters.lord_id');
})
->get();
if($user->count()) {
$user = $user->first();
return View::make('layout.profile')
->with('user', $user)
->with('char', $char);
}
return App::abort(404);
}
}
In my code I will redirect to this route with the following:
return Redirect::route('user-profile', Session::get('theuser'));
In the view I just want to do:
Welcome back, {{ $user->username }}, your main character is {{ $char->char_name }}
My problem is that I will receive this error: Trying to get property of non-object in my view. I am sure it is referring to $char->char_name. What's going wrong? I have a very difficult time understanding Laravel. I don't know why. Thanks in advance!
You should be using the Auth class to get the session information for the logged in user.
$user = Auth::user();
$welcome_message = "Welcome back, $user->username, your main character is $user->Character->char_name";
You don't need to pass anything to that route either. Simply check if the user is logged in then retrieve the data. You have access to this data from anywhere in your application.
if (Auth::check())
{
//the user is logged in
$user = Auth::user();
To answer your question in the comments, reading the documentation would solve all of these problems, however:
public function user()
{
if (Auth::check())
{
$user = Auth::user();
return View::make('rtfm', compact('user'));
}
else
{
return "The documentation explains all of this very clearly.";
}
}