I have a controller like this
use App\Model\User;
class UserController extends BaseController
{
protected $model;
public function __construct(User $user)
{
$this->model = $user;
}
public function updatePhone(Request $request)
{
//user id
$id = $request->id;
//new phone number
$phone = $request->phone;
}
}
The function updatePhone is used to update the phone number of the user.So I can code like this
$res = $this->model->where('id',$id)->update('phone',$phone)
In this way, I do nothing in the user model.But I get used to like this
$res = $this->model->updatePhone($id, $phone);
And I must create function updatePhone in user model
public function updatePhone($id,$phone)
{
return $this->where('id',$id)->update('phone',$phone);
}
who is the better way to update a single model? Any answers or suggestions are excepted.
Related
I have tables called users, places and user_place. users has a column called id that contains the id of the user and places has a column called place_id as well. The user_place table has 2 columns called user_id and place_id and I'm trying to automatically populate them with the corresponding ids. I read I have to use attach() function after setting up the relationships which I believe I have done but I might be wrong. Here they are:
class PlaceController extends Controller
{
public function likePlace(Request $request){
$placeId = $request['placeId'];
$userId = $request['userId'];
$user = User::where('id', $userId)->first();
$place = new Place();
$place->place_id = $placeId;
$place->save();
$user->places()->attach($place);
}
}
User model:
class User extends \Eloquent implements Authenticatable
{
use AuthenticableTrait;
public function places(){
return $this->hasMany('App\Place');
}
}
Place mode:
class Place extends Model
{
public function user(){
return $this->belongsToMany('App\User');
}
}
In a Many to Many relationship, you should define both relationships like the following:
User.php
class User extends \Eloquent implements Authenticatable
{
use AuthenticableTrait;
public function places()
{
return $this->belongsToMany('App\Place', 'user_place', 'user_id', 'place_id');
} // ^^^^^^^^^^^^
}
Note: Given that your intermetiate table name doesn't follow the naming convention we specified so Laravel knows where table to look up.
Place.php
Notice that you mentioned that the primmary key of your Place model is place_id, and this also scapes from the Laravel convention you should specify it:
protected $primaryKey = 'place_id'; // <----
class Place extends Model
{
public function user()
{
return $this->belongsToMany('App\User', 'user_place', 'place_id', 'user_id');
}
}
So now in your controller:
class PlaceController extends Controller
{
public function likePlace(Request $request)
{
$placeId = $request['placeId'];
$userId = $request['userId'];
$user = User::where('id', $userId)->first();
$place = new Place();
$place->place_id = $placeId;
$place->save();
$user->places()->attach($place);
}
}
Side note
As I side note, you could save a couple of line replacing some sentences with their equivalent:
$userId = $request['userId'];
$user = User::where('id', $userId)->first();
Using the find() method, this is equal to:
$user = User::find($request['userId']);
Then, you could create your related object using the static method create of an Eloquent model so this:
$placeId = $request['placeId'];
$place = new Place();
$place->place_id = $placeId;
$place->save();
Is equal to this:
$place = Place::create(['place_id' => $request['placeId']]);
Then your controller will be reduced to this:
class PlaceController extends Controller
{
public function likePlace(Request $request)
{
$user = User::find($request['userId']);
$place = Place::create(['place_id' => $request['placeId']]);
$user->places()->attach($place);
}
}
I am working on notifications I have 2 tables: one is notify and the other is notify_status. Through notify I am showing data like title and description and in notify_status I have field read_status which is by default 0. After I show it I want to change it to 1. I also have notify_id in it as a foreign key. This is my show method:
public function show($id)
{
$notify = Notify::find($id);
$notify_status = NotifyStatus::where('notify_id', $id)->get();
$user_data['read_status'] = 1;
$user = NotifyStatus::create($user_data);
return view('notify.desr')->with(compact('notify'));
}
But it isn't creating against notify_id. What should I do?
Your models should define the following relationships:
class Notify extends Model
{
public function setAsRead()
{
$this->status->read_status = 1
$this->status->save();
}
public function wasRead()
{
return (bool) $this->status->read_status;
}
public function status()
{
return $this->hasOne(NotifyStatus::class);
}
}
class NotifyStatus extends Model
{
public function notify()
{
return $this->belongsTo(Notify::class);
}
}
Take a look at Laravel Eloquent Relationships for further reading.
In your controller you can use it like:
$notify = Notify::find($id);
$notify->status->read_status = 1;
$notify->status->save();
return view('notify.desr')->with(compact('notify'));
Or you can simply create a new method to set the new status (take a look at first method of Notify class):
$notify = Notify::find($id);
$notify->setAsRead();
return view('notify.desr')->with(compact('notify'));
public function show($id)
{
$notify = Notify::find($id);
$notify_status = NotifyStatus::where('notify_id', $id)->first();
$notify_status->read_status = 1;
$notify_status->save()
return view('notify.desr')->with(compact('notify'));
}
When I am trying to send mail, everytime a new member is added to the user table, so that they can get a setup password link. I have been trying to get this to work but seem not to be.
public function store(AddUser $request)
{
$user = $request->all();
$user['activate'] = $this->active();
$user['guid'] = $this->guid();
$user['accountno'] = $this->generateAndValidateAccountno();
$check = User::find($user['phone']);
if(!$check) {
$id = User::create($user);
$this->sendEmail($user['accountno']);
}
return redirect('employee');
}
public function sendEmail(Request $request, $id)
{
$user = User::find($id);
Beautymail::send('emails.welcome', [], function($message)
{
$message
->to('$id->email', '$id->fname')
->subject('Welcome!');
});
}
}
Not sure what am doing wrong
Just use the same request class in the controller and the model. In your user model, add use Illuminate\Http\Request at the top of the class to tell it which Request class to use.
Just change:
public function sendEmail(Request $request, $id){...}
to
public function sendEmail($id){...}
Im having trouble trying to get my model observer to work.. It is working as expected for create and deleted, but not for updating. Im guessing the event never fires. The thing is all of then are being done exactly the same way. Any ideas?
Below, my observer.
class GenericObserver extends AbstractObserver {
protected $events;
public function __construct(Dispatcher $dispatcher){
$this->events = $dispatcher;
}
public function saved($model) {
dd($this->events);
$user_id = Auth::user()->usr_id;
$user_nome = Auth::user()->usr_nome;
$user_email = Auth::user()->usr_email;
dd($model);
}
public function deleted($model) {
$user_id = Auth::user()->usr_id;
$user_nome = Auth::user()->usr_nome;
$user_email = Auth::user()->usr_email;
echo($model->getTable());
dd($model->getKeyName());
}
public function updated($model) {
$user_id = Auth::user()->usr_id;
$user_nome = Auth::user()->usr_nome;
$user_email = Auth::user()->usr_email;
dd($model);
}
public function saving($model){
echo 'Saving';
}
public function deleting($model){
echo 'Deleting';
}
public function updating($model){
echo 'Updating';
}
And here, my model class
Aplicacao extends Model {
protected $table = 'gst_aplicacoes';
protected $primaryKey = 'app_id';
protected $fillable = ['app_nome', 'app_key', 'app_observacao'];
public static function table() {
$model = new static;
return $model->getTable();
}
public static function boot() {
parent::boot();
Aplicacao::observe(new GenericObserver(new Dispatcher));
}
If anyone ever faces this issue, the reason the event was not firing was because the update method, only fire its events when the update happens directly on the model, since i was using an intermediary repository to represent my model, it wasn't working.
for more details.
https://github.com/laravel/framework/issues/11777#issuecomment-170388067
Observer work on only save() method. And it's not working on function of query builder that you call by magic methods. So on update() and created() observer is not work.
This will work:
Model::find($id)->update(['column' => $value]);
I have function showItemList inside User class
class User extends Eloquent {
//...
protected $item = ['axe', 'sword', 'knife'];
public function showItemList() {
return $this->$item;
}
}
In my controller it's possible to use this.
$id = 1;
$user = User::find($id);
$user -> showItemList();
But how can I just call this function directly(irrelevant to $id query)?
I looks for something like below (sure now it's not working):
$list = User::showItemList();
You need to use the static protected variable and return it from static method.
class User extends Eloquent {
//...
static protected $item = ['axe', 'sword', 'knife'];
public static function showItemList() {
return self::$item;
}
}