I'm trying to create a user profile and store it into database using laravel repositories .
below is my controller code :
<?php
namespace App\Http\Controllers;
use App\Http\Requests\UsercreateRequest;
use App\Http\Requests\UserupdateRequest;
use App\Repositories\UserRepository;
use Illuminate\Http\Request;
class UserController extends Controller
{
protected $userRepository;
protected $nbrPerPage=4;
public function __construct(UserRepository $UserRepository)
{
$this->userRepository=$UserRepository;
}
public function index()
{
return view('signup');
//
}
public function create()
{
return view('signup');
//
}
public function store(UsercreateRequest $request)
{
$image =$request->file('image');
if($request->hasFile('image'))
{
if($image->isValid())
{
$way=public_path('images');
$extension=$image->getClientOriginalExtension();
do
{
$name=$image->getClientOriginalName();
//echo $name;
}while(file_exists($way.'/'.$name));
if($image->move($way,$name))
{
echo'ok '; //75485205
//echo $name;
$user=$this->userRepository->store($request->all(), $request);
return redirect('dashboard')->withOk(" L'enrisgrement n'a pas abouti !");
}
}
}
return redirect('signup')->withOk(" L'enrisgrement n'a pas abouti !");
//
}
public function show($id)
{
$user=$this->userRepository->getByid($id);
return view('dashboard', compact('user'));
//
}
public function edit($id)
{
$user=$this->userRepository->getByid($id);
return view('dashboard', compact('user'));
//
}
public function update(UserupdateRequest $request, $id)
{
$this->userRepository->update($id, $request->all());
return view('dashboard');
//
}
public function destroy($id)
{
$this->userRepository->destroy($id);
return back();
//
}
}
The model is also as below
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','image',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
My repository
<?php
namespace App\Repositories;
use App\User;
use App\Http\Requests\UsercreateRequest;
class UserRepository{
protected $user;
public function __construc(User $user)
{
$this ->user=$user;
}
private function save (User $user, Array $inputs, UsercreateRequest $request)
{
$user->name=$inputs['name'];
$user->email=$inputs['email'];
$image=$request->file('image');
$name=$image->getClientOriginalName();
$user->image=$name;
$user->save();
}
public function store(Array $inputs,UsercreateRequest $request)
{
$user= new User();
$user->password=bcrypt($inputs['password']);
$this->save($user,$inputs,$request);
}
public function getByid ($id)
{
return $this->user->findOrfail($id);
}
public function update($id, Array $inputs)
{
$this->save($this->getByid($id),$inputs);
}
public function destroy ($id)
{
$this->getByid($id)->delete();
}
}
In my save function when i simply write $user->image=inputs['image'] it works but instead of the image name its store a path to my socket . how can i use getClientOriginalName() here to get the client image and store it in the database ?
any idea ?
Thanks
Change your store method call to this.
$data = array_merge($request->all(), ['image' => $name]);
$user = $this->userRepository->store($data, $request);
PS : The loop checking if the file already exists is useless. The loop will never end if an image with the same name as the uploaded file already exists.
do {
$name = $image->getClientOriginalName();
} while(file_exists($way.'/'.$name));
To fix this you should throw in some random name generator here.
Related
Im using system where it is using $user->is_admin and $user->is_employee and $user->is_customer there is no column is_admin or is_employee or is_customer in database. I know that it takes it from user model. but is_admin or is_employee is not defined anywhere. and dumping gives me true or false.
I want add new checking like is_manager. but cant find where I can add this..
Debugbar isnt showing any query for is_admin column..
Where it can be located?
example I have observer:
use App\Helper\SearchLog;
use App\User;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
class UserObserver
{
public function roleAttached(User $user, $role, $team)
{
if (!$user->is_admin) {
$type = 'Employee';
$route = 'admin.employee.edit';
if ($user->is_customer) {
$type = 'Customer';
$route = 'admin.customers.show';
}
SearchLog::createSearchEntry($user->id, $type, $user->name, $route);
SearchLog::createSearchEntry($user->id, $type, $user->email, $route);
}
}
I dont understand how it knows is_admin if it is not in database column?
My user model:
namespace App;
use App\Observers\UserObserver;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laratrust\Traits\LaratrustUserTrait;
class User extends Authenticatable
{
//------------------------------------ Traits ---------------------------
use LaratrustUserTrait;
use Notifiable;
//------------------------------------ Attributes ---------------------------
protected static function boot() {
parent::boot();
static::observe(UserObserver::class);
static::laratrustObserve(UserObserver::class);
}
/**
* 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',
];
protected $appends = [
'user_image_url', 'mobile_with_code', 'formatted_mobile'
];
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = ['deleted_at'];
//------------------------------------ Relations ----------------------------
public function employeeGroup() {
return $this->belongsTo(EmployeeGroup::class, 'group_id');
}
public function todoItems() {
return $this->hasMany(TodoItem::class);
}
public function completedBookings() {
return $this->hasMany(Booking::class, 'user_id')->where('bookings.status', 'completed');
}
public function booking() {
return $this->belongsToMany(Booking::class);
}
public function services() {
return $this->belongsToMany(BusinessService::class);
}
public function leave()
{
return $this->hasMany('App\Leave', 'employee_id', 'id');
}
public function role()
{
return $this->belongsToMany(Role::class);
}
public function employeeSchedule()
{
return $this->hasMany('App\EmployeeSchedules', 'employee_id', 'id');
}
//------------------------------------ Scopes -------------------------------
public function scopeAllAdministrators() {
return $this->whereHas('roles', function ($query) {
$query->where('name', 'administrator');
});
}
public function scopeAllCustomers() {
return $this->whereHas('roles', function ($query) {
$query->where('name', 'customer')->withoutGlobalScopes();
});
}
public function scopeOtherThanCustomers() {
return $this->whereHas('roles', function ($query) {
$query->where('name', '<>', 'customer');
});
}
public function scopeAllEmployees() {
return $this->whereHas('roles', function ($query) {
$query->where('name', 'employee');
});
}
//------------------------------------ Accessors ----------------------------
public function getUserImageUrlAttribute() {
if (is_null($this->image)) {
return asset('img/default-avatar-user.png');
}
return asset_url('avatar/' . $this->image);
}
public function getRoleAttribute() {
return $this->roles->first();
}
public function getMobileWithCodeAttribute() {
return substr($this->calling_code, 1).$this->mobile;
}
public function getFormattedMobileAttribute() {
if (!$this->calling_code) {
return $this->mobile;
}
return $this->calling_code.'-'.$this->mobile;
}
public function routeNotificationForNexmo($notification) {
return $this->mobile_with_code;
}
public function getIsAdminAttribute() {
return $this->hasRole('administrator');
}
public function getIsEmployeeAttribute() {
return $this->hasRole('employee');
}
public function getIsCustomerAttribute() {
if ($this->roles()->withoutGlobalScopes()->where('roles.name', 'customer')->count() > 0) {
return true;
}
return false;
}
//------------------------------------ Mutators -----------------------------
public function setPasswordAttribute($value) {
$this->attributes['password'] = bcrypt($value);
}
//------------------------------------ Formats -----------------------------
public function userBookingCount($date) {
return Booking::whereNull('deal_id')->where('user_id', $this->id)->whereDate('created_at', $date)->get()->count();
}
} /* end of class */
LoginController looks like this where is authenticated class:
protected function authenticated(Request $request, $user)
{
if ($user->is_admin || $user->is_employee) {
return redirect()->route('admin.dashboard');
}
if(!$user->is_admin && !$user->is_employee && Cookie::get('bookingDetails')!==null && Cookie::get('products')!==null && $this->checkUserBooking($user->id)>$this->settings->booking_per_day){
return redirect(route('front.index'))->withCookie(Cookie::forget('bookingDetails'))->withCookie(Cookie::forget('products'))->withCookie(Cookie::forget('couponData'));
}
return redirect(session()->get('url.encoded'));
}
You can make another accessor that will check if role is associated with current user entity.
public function getIsManagerAttribute() {
return $this->hasRole('manager');// presuming you have created manager role
}
Then you can check easily with
// $user = User::find(1);
// $user->is_manager;// true || false
I have an user model and a student model which I have created relationship for, but when I try to
$student->user->fullname
I get this error
"trying to get property fullname of non-object"
here is my user model code:
<?php
namespace App;
use App\Assignment;
use App\Model\Quiz;
use App\Model\Course;
use App\Topic;
use App\Model\Guardian;
use App\Model\Student;
use App\Model\Teacher;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, HasRoles, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'fullname',
'email',
'avatar',
'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function setPasswordAttribute($password)
{
$this->attributes['password'] = bcrypt($password);
}
public function guardian()
{
return $this->belongsTo(Guardian::class);
}
public function teacher()
{
return $this->belongsTo(Teacher::class);
}
public function student()
{
return $this->belongsTo(Student::class);
}
public function assignments()
{
return $this->hasMany(Assignment::class);
}
public function quizzes()
{
return $this->hasMany(Quiz::class);
}
public function courses()
{
return $this->hasMany(Course::class);
}
public function topics()
{
return $this->hasMany(Topic::class);
}
public function levels()
{
return $this->hasMany(Level::class);
}
}
and here is my student model code
<?php
namespace App\Model;
use App\User;
use App\Model\Course;
use App\Assignment;
use App\Level;
use App\Model\DoneQuiz;
use App\Model\Teacher;
use App\Model\Guardian;
use Illuminate\Database\Eloquent\Model;
class Student extends Model
{
protected $fillable = ['user_id', 'level_id', 'guardian_id'];
public function user()
{
return $this->belongsTo(User::class);
}
public function courses()
{
return $this->hasMany(Course::class);
}
public function assignments()
{
return $this->hasMany(Assignment::class);
}
public function level()
{
return $this->hasOne(Level::class);
}
public function teachers()
{
return $this->hasMany(Teacher::class);
}
public function guardian()
{
return $this->hasOne(Guardian::class);
}
public function donequizzes()
{
return $this->hasMany(DoneQuiz::class);
}
}
and even when I try to use this relationship to get data like
'student_id' => auth()->user()->student()->id
I get this error
"BadMethodCallException Call to undefined method
Illuminate\Database\Eloquent\Relations\BelongsTo::id()"
when you use student() it returns a query builder
Either change it to simple student
'student_id' => auth()->user()->student->id
OR
'student_id' => auth()->user()->student()->first()->id
This is my PlayerController, Player & Session Model and Resource.
I want to use the input (sessionId from SessionsTable) to fetch user from the room with the same id (userSession) and return an array in this format: [{userId:1, userName: stacki, userVote:8},{...},...]
I already asked [here][1] to achieve this and now im stuck with this error.
What do I have to change in order to solve this issue? Simply adding ->first() does not solve my issue, I need more than one record.
namespace App\Http\Controllers;
use App\Player;
use Illuminate\Http\Request;
use App\Http\Resources\Players as PlayerResource;
class PlayerController extends Controller
{
public function index(Request $request)
{
$room = $request->input('sessionId');
$currentPlayers = Player::where('userSession', $room)->get();
return PlayerResource::collection($currentPlayers);
}
public function create()
{ }
public function update()
{ }
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Player extends Model
{
protected $fillable = [];
public $sortable = [
'userId',
'userName',
'userVote'
];
public function sessions()
{
return $this->hasMany('App\Session');
}
public function players(){
return $this->belongsToMany('App\Session');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Session extends Model
{
protected $fillable = [];
public function user(){
return $this->belongsToMany('App\Player');
}
public function creator()
{
return $this->hasOne('App\Player', 'userId');
}
}
class Players extends ResourceCollection
{
/**
* Transform the resource collection into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'userId' => $this->sessionId,
'userName' => $this->userName,
'userVote' => $this->userVote
];
}
}
`
[1]: https://stackoverflow.com/questions/58062014/display-db-entries-in-json-array-in-controller-laravel-php
Your Player class might extends the Illuminate\Http\Resources\Json\JsonResource instead of ResourceCollection.
This should solve your problem.
use Illuminate\Http\Resources\Json\JsonResource;
class Players extends JsonResource
{
/**
* Transform the resource collection into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'userId' => $this->sessionId,
'userName' => $this->userName,
'userVote' => $this->userVote
];
}
}
Hope it helps.
I just made a delete function of accounts, but I'm stuck on a problem.I need to also delete posts of user, at delete account.How can I make that? I have table Users, where I have all details from users, and table Posts, where also have user_id and id,caption and image of post.
public function delete($id)
public function delete($id)
{
$profile = User::find($id);
$profile->delete();
Session::flash('remove', "The profile was successfully deleted!");
return redirect('login');
}
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $guarded = [];
public function profileImage(){
$imagePath = ($this->image) ? $this->image : 'profile/vx2k9TEhkcgaRdOWKvs4lsxqOVmuzwumtwySEnvH.png';
return '' . $imagePath;
}
public function user(){
return $this->belongsTo(User::class);
}
public function followers(){
return $this->belongsToMany(User::class);
}
}
User.php
<?php
namespace App;
use App\Mail\NewUserWelcomeMail;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Mail;
use Actuallymab\LaravelComment\CanComment;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'username', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
static::created(function ($user) {
$user->profile()->create([
'title' => $user->username,
]);
});
}
public function posts()
{
return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
}
public function profile()
{
return $this->hasOne(Profile::class);
}
}
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}
public function likes()
{
return $this->hasMany('App\Like');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
Migration posts table
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('caption');
$table->string('image');
$table->timestamps();
$table->index('user_id');
});
}
I think you could try to delete related model in the controller before the user, i.e.:
public function delete($id)
{
$profile = User::find($id);
$profile->posts()->delete();
$profile->delete();
Session::flash('remove', "The profile was successfully deleted!");
return redirect('login');
}
Or you can go with model event, i.e.:
protected static function boot() {
parent::boot();
static::created(function ($user) {
$user->profile()->create([
'title' => $user->username,
]);
});
static::deleting(function($user) {
$user->posts()->delete();
});
}
I am using this code part many times without problem. But this time $success return null and i couldn't figure out. When i check database, i see User 1 is updated. Since it's saving there is no fillable problem. Also i tried save() function too. What am i missing? Thanks for help.
(Laravel version 5.2.45)
$user = User::find(1);
$user->firstname = $request->firstname;
$user->lastname = $request->lastname;
$success= $user->update(); // Database update is successful
dd($success); // But return null
User model
<?php
namespace App;
use App\Presenters\UserPresenter;
use App\Services\Logging\UserActivity\Activity;
use App\Support\Authorization\AuthorizationUserTrait;
use App\Support\Enum\UserStatus;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Zizaco\Entrust\Traits\EntrustUserTrait;
class User extends Model implements AuthenticatableContract, AuthorizableContract, CanResetPasswordContract
{
use CanResetPassword, AuthorizationUserTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
protected $dates = ['last_login', 'birthday'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $guarded = [];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function items()
{
return $this->hasMany('App\Item');
}
/**
* Always encrypt password when it is updated.
*
* #param $value
* #return string
*/
public function setPasswordAttribute($value)
{
$this->attributes['password'] = bcrypt($value);
}
public function gravatar()
{
$hash = hash('md5', strtolower(trim($this->attributes['email'])));
return sprintf("//www.gravatar.com/avatar/%s", $hash);
}
public function isUnconfirmed()
{
return $this->status == UserStatus::UNCONFIRMED;
}
public function isActive()
{
return $this->status == UserStatus::ACTIVE;
}
public function isBanned()
{
return $this->status == UserStatus::BANNED;
}
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
public function activities()
{
return $this->hasMany(Activity::class, 'user_id');
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthpassword()
{
return $this->password;
}
public function getAuthIdentifierName()
{
return $this->getKeyName();
}
public function verification()
{
return $this->hasOne('App\Verification');
}
}
Update Question (New Try):
I tried empty controller with just update function. I still get failure.
UserController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Auth;
use Illuminate\Http\Request;
class UserController extends Controller
{
public function getEdit()
{
$user = User::find(1);
return view('user.editprofile', compact('user'));
}
public function postEdit(Request $request)
{
$user = User::find(1);
$user->firstname = $request->firstname;
$user->lastname = $request->lastname;
if($user->update())
{
echo "Success";
}
echo "Fail"; // Print "Fail" but update was successful.
}
}
When successfully inserted or updated records , laravel return true on success and false on failure and also you can check like this.
if($user->save()){
//do something when user is save
}else{
// do something wehn user is not update
}
or
if($user->update()){
//do something when user is update
}else{
// do something wehn user is not update
}
I usually did this for make sure is saved successfully
try {
DB::beginTransaction();
// save or update happen in here
DB::commit();
} catch (\Exception $e) {
DB::rollback();
// something happen in here when error
}
for
DB::beginTransaction();
DB::commit();
DB::rollback();
is optional but I recommend it cause when anything bad happen in the middle it will rollback the saved data for you.
Try update user using array. Like this
$user = User::find(1);
$dataToUpdate['firstname'] = $request->firstname;
$dataToUpdate['lastname'] = $request->lastname;
if($user->update($dataToUpdate))
{
echo "Success";
}
echo "Fail"; // Print "Fail" but update was successful.
Also you can try to add:
protected $fillable = ['firstname', 'lastname'];
to your User.php Model
I figured out problem. There is a trait which override save and update function.
use App\Support\Authorization\AuthorizationUserTrait