I'm trying to merge current user id with with a laravel $request and aftr merging all data will be saved into DB. After execution data save into DB but id save as a null value. Please see my code
public function store(Request $request, ClassModel $model)
{
$model->create($request->merge(['created_user_id' => Auth::user()->id])->all());
return redirect()->route('class.index')->withStatus(__('Class successfully created.'));
}
Can anyone tell me why user id dont save in DB.
Your field is probably nullable but then in your $fillable array of the model (which is used for mass assignment protection), you forgot to include the created_user_id column. Please check that.
Related
I have small laravel function called from ajax. Then I have to return result to ajax result. For example
Public function Edit(Request $request){
$user = User::find($request->id);
//.........
return response()->json($user);
}
But I have problem on 'salary' property because of It getting from getSalaryAttribute method
public function getPositionnameAttribute(){
...........
}
So, at the ajax result return 'undefined', that reasonable because 'salary' property does not exist. I do not need to made specific collection to handle only salary parameter.
Any advise or guidance would be greatly appreciated, Thanks.
You have two options:
add protected $appends = ['salary'] to your model
or
append it on run time: $user->append('salary')->toArray();
Check out the docs: https://laravel.com/docs/5.8/eloquent-serialization#appending-values-to-json
Appending At Run Time add this attribute to $attributes array,
The append method. Or, you may use the setAppends method to override the entire array of appended properties for a given model instance.
return $user->append('salary')->toArray();
return $user->setAppends(['salary'])->toArray();
You need to add this attribute to $appends array.
Model
protected $appends = ['position_name'];
NOTE: The $hidden and $appends feature (written above) is for modeling of JSON data and will not effect blade access to properties and/or model renderings.
https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json
I'm creating an advert like this
public function store(Request $request)
{
$advert = PropertyAdvertisement::create($request->all());
return response()->json($advert);
}
What is the best way to attach a user_id on the advert model?
After creating, add a line before the return to give the field to the $advert variable (assuming user_id is a fillable field on the PropertyAdvertisement model and your request is routed through the Auth middleware):
$advert->user_id = \Auth::user()->id;
$advert->save();
Or if you want less code, add the user_id to the $request object in advance of creation:
$request['user_id'] = \Auth::user()->id
I have below code that fetches users and relational role object for each user.
$query = (new UserModel())->newQuery();
$query->with("Role");
$data = $query->get(["UserName", "EmailAddress", "User_ID"]);
I have 3 roles present in database and they are in cache.
Is there any way to change this line of code: $query->with("Role"); such that while fetching the users each time, it will not need to fetch roles from database.
Maybe you can hook into the Retrieved event from Eloquent. When retrieving the model from the Database you can fetch the role from the cache and set it on the model. Perhaps that could be a solution for you?
Take a look at the Laravel Docs on eloquent events here: https://laravel.com/docs/5.6/eloquent#events
Maybe this will work out something for you, add this to your model class:
/**
* Boot the model.
*/
protected static function boot()
{
parent::boot();
static::retrieving(function ($user) {
$user->fetchFromCache("Role"); //replace this line with however you could fetch it from the cache
});
}
I'm using Laravel 5 and I created a resource controller, setup routing and setup my database model.
My question is: when I do a POST, my store method is called on the controller but how can I take the request data and insert a new entry in the db without having to explicitly set every field?
Here's my code:
public function store(Request $request)
{
$data = $request->all(); // this grabs all my request data - great!
$user = new User;
$user-> ??? // insert ALL posted data
$user->save();
}
I understand that I can do...
$user->name = $request->name;
...for every field. But can someone tell me how to insert everything?
I realize I can probably do a foreach but I'm wondering if there's something better.
There is method fill in every model https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html#method_fill:
$user->fill($request->all());
Eventually you can use create:
\User::create($request->all());
This above is called mass asignment and there is section about this in Eloquents documentation https://laravel.com/docs/5.1/eloquent
You need to define which keys might be set:
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// The attributes that are mass assignable
protected $fillable = ['name', 'login', 'birthdate'];
}
Okey, I'm newbie in Laravel and I want to do a function in my controller that returns a JSON with the all lists of one user, i want to filter users by email, that isn't the primary key, but I'm having a lot of problems here, and the documentation of laravel didn't explain nothing about this.
Okey so i have a class User with this atributes and relationships:
User.php
protected $fillable = [
'nom', 'email', 'password', 'data_de_naixament', 'sexe', 'type', 'imatge_usr', 'codi_postal'
];
public function lists()
{
return $this->hasMany('App\List');
}
And another class List:
List.php
protected $fillable = ['nom_llista', 'id_user'];
public function user()
{
return $this->belongsTo('App\User', 'id_user');
}
So I know that I have to do a JOIN and compare the input parameter with the email colum of the User table but I can not get it because they do not understand at all the syntax eloquent.
I'm able to do a function that store all lists and then filtering by email, but this isn't efficient if I have 2000 lists for example.
Hope you can help me and sorry for my poor English.
You should read the documentation
To retrieve information: https://laravel.com/docs/5.1/eloquent#retrieving-multiple-models
To convert a collection to json: https://laravel.com/docs/5.1/collections#method-tojson
Joining Models:
https://laravel.com/docs/5.1/eloquent-relationships#querying-relations
In other words your code could be like
$users = User::where('email', $emailYouAreLookingFor)->with('lists')->get()->toJson();