Laravel, get id from newly created object - laravel

i'm using laravel 5.2 and i need get the id of the newly created object in the same function in a controller to create another object with this attribute.
This is the function in the controller:
public function store(Request $request)
{
Movie::create([
'usuario_id' => $request['usuario_id'],
'asignatura_id' => $request['asignatura_id'],
'name' => $request['name'],
'visit' => $request['visit'],
'language' => $request['language'],
]);
Subtitle::create([
'url' => $request['subtitle'],
]);
return "OK";
}
I need the id of this Movie to create a new Subtitle because the id is a foreign key in Subtitle. Thanks for the answers.

You can get the Id by assigning the created object to a new variable.
public function store(Request $request)
{
$movie = Movie::create([
'usuario_id' => $request['usuario_id'],
'asignatura_id' => $request['asignatura_id'],
'name' => $request['name'],
'visit' => $request['visit'],
'language' => $request['language']
]);
Subtitle::create(['url' => $request['subtitle']]);
$movieId = $movie->id; //replace `id' with your real ColumnName. Same way you can retrieve all other Columns
return "OK";
}

Related

Undefined method 'posts' inside controller - Laravel

I am getting error for undefined method which is defined inside my User model.
My controller:
$inputs = request()->validate([
'title' => 'required|min:8|max:255',
'post_image' => 'file',
'body' => 'required'
]);
auth()->user()->posts()->create($inputs);
My Post model:
public function user() {
return $this->belongsTo('App\Models\User');
}
My User model:
public function posts() {
return $this->hasMany('App\Models\Post');
}
correct your relationship
public function posts() {
return $this->hasMany(Post::class);
}
First your posts relationship is wrong, it must be hasMany NOT belongsTo
public function posts() {
return $this->hasMany(User::class);
}
Then it should work.
You can also try to create the model in a different way:
$validated = request()->validate([
'title' => 'required|min:8|max:255',
'post_image' => 'file',
'body' => 'required'
]);
// Here you should check if $validated has all required fields
// because some could fail, in that case aren't in the array
Post::create([
'title' => $validated['title'],
'user_id' => auth()->id, // or auth()->user->id
'post_image' => $validated['post_image'],
'body' => $validated['body'],
]);
Laravel Validation Docs

I have a problem with laravel validation logic when im trying to update my data

Hello guys im beginner in laravel and i need some help.I have a problem with my validation.When i store data in my bootstrap modal everyting is fine but when i press edit button and want to update, the same validation logic applies like when i create.When I want to update, if i don't change the name it won't update because it must be unique.
This is my Department Controller
public function store(Request $request)
{
$this->validate($request,[
'name'=>"required|unique:departments|max:255"
]);
$departmentId = $request->department_id;
Department::updateOrCreate(
['id' => $departmentId],
['name' => $request->name, 'description' => $request->description]
);
return response()->json(['success'=>'Department saved successfully.']);
}
As previously mentioned it would be ideal to have this be 2 different methods, but if you want this in one method you can achieve that. You will need to check if that department id is being passed or not to see if this is an update or create, then adjust the rule based on this. You can try something like this:
public function store(Request $request)
{
$unique = \Illuminate\Validation\Rule::unique('deparments');
if ($request->has('deparment_id')) {
$unique->ignore($request->department_id);
}
$this->validate($request, [
'name' => [
'required', $unique, 'max:255',
],
]);
$departmentId = $request->department_id;
Department::updateOrCreate(
['id' => $departmentId],
['name' => $request->name, 'description' => $request->description]
);
return response()->json(['success'=>'Department saved successfully.']);
}
This assumes the deparment_id is only passed for updates.
you can do this :-
$this->validate($request,[
'name' => 'required|unique:departments|max:255,'. $request->department_id,
]);

Call to undefined method App\User::events()

I am trying to store data into the database, but the error I'm getting is:
Call to undefined method App\User::events()
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'slug' => 'required|unique:events',
'body' => 'required',
'date' => 'date_format:M-d-y H:i:s',
'time' => 'required'
]);
$request->user()->events()->create($request->all());
return redirect('/backend/blog')->with('message', 'Your event was created successfully');
}
Try this:
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'slug' => 'required|unique:events',
'body' => 'required',
'date' => 'date_format:M-d-y H:i:s',
'time' => 'required'
]);
$user = User::create($request->all()); // create the user
event(new UserRegistered($user)); // Add your own event class name.
return redirect('/backend/blog')->with('message', 'Your event was created successfully');
}
Note: Assuming that you have created the UserRegistered event. And call it by event helper method.
It seems like you do not have any events() relationship in you User model.
Assuming you have Event model, you can write like in User model:
public function events()
{
return $this->hasMany(Event::class);
}

Update two tables using one function in Laravel

I'm building an app using Laravel 5.7 and Vue.js2. I have two tables: departments and users. A user can be a chief of a department. I made the relationship between the models. I want it so that when I create a new department, the type of the chief will be changed on the user's table to 'chief.'
DepartmentController
public function store(Request $request)
{
$this->validate($request, [
'name' => 'string|required|max:191',
'bio' => 'string|required',
'user_id' => 'integer|required|unique:departements'
]);
return Department::create([
'name' => $request['name'],
'user_id' => $request['user_id'],
'bio' => $request['bio']
]);
}
Can you try this.
Controller
public function store(Request $request)
{
$this->validate($request,[
'name'=>'string|required|max:191',
'bio'=>'string|required',
'user_id'=>'integer|required|unique:departements'
]);
$new_department = Department::create([
'name'=>$request['name'],
'user_id'=>$request['user_id'],
'bio'=>$request['bio']
]);
$get_user = User::where('id', $request['user_id'])->first();
if($get_user)
{
$get_user->type = 'chief';
$get_user->save();
}
return ['message' => 'success'];
}
In this code, After saving the New Department I get the UserData in UserModel where id is the $request['user_id] then check it if exists.
If exists, I change the type to 'chief' and save.
If you have relationship between two models then you can update like this
$product = Department::with('relationship_function_name')->find($id);
$product->fields= $request->input_name;
$product->relationship_function_name->field_name = $request->input_name;
$product->update();
Hope this helps :)

Method Illuminate\Database\Query\Builder::profilesInfoModel does not exist. // RegisterController.php

what i need is to save some data besides creating the user, here is what I've been trying to do in my RegisterController.php :
protected function create(array $data)
{
if (isset($data['checkbox'])) {
$type = 1;
$available = 1;
} else {
$type = 0;
$available = 0;
}
$user = User::create([
'name' => $data['name'],
'username' => $data['username'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'type' => $type,
'available' => $available,
'company' => $data['company'],
'job' => $data['job'],
]);
$user->profilesInfoModel()->create([
'bio' => $data['bio'],
'site' => $data['site'],
'location' => $data['location'],
'education' => $data['education'],
]);
return $user->with('profilesInfoModel');
}
The User.php (Model) has a one to one relationship with profilesInfoModel (yes, i know i should change the name of the model to make it more comfortable).
But after trying to register a user... i get this error message: Method Illuminate\Database\Query\Builder::profilesInfoModel does not exist.
What is actually going on?
The relationship should be like this
User Model
public function profile()
{
return $this->hasOne(ProfileInfo::class, 'user_id');
}
Assuming you have ProfileInfo as Profile model and it has user_id as foreign key references users table id field
Now you can create profile from $user like this
$user->profile()->create([
'bio' => $data['bio'],
'site' => $data['site'],
'location' => $data['location'],
'education' => $data['education'],
]);
$user->load('profile'); //lazy eager load
return $user;
1.in App\Model\User
public function profilesInfoModel()
{
return $this->hasOne(App\Model\User);
}
2.to call
use App\Model\User
in RegisterController

Resources