Update two tables using one function in Laravel - 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 :)

Related

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,
]);

Returning laravel realtionship within json

I am currently doing this as title says like this:
$user = User::where('username', request('username'))->first();
$posts = [];
$comments = [];
foreach($user->posts as $post){
foreach($post->comments as $comment){
array_push($comments, [
'id' => $comment->id,
'body' => $comment->body,
'user' => $comment->user->only(['name', 'id']),
]);
}
array_push($posts, [
'title' => $post->title,
'id' => $post->id,
'body' => $post->body,
'comments' => $comments,
]);
}
return response()->json([
'user' => $user->only(['name', 'avatar', 'age']),
'posts' => $posts,
]);
Is there a shorter way of doing this like:
$user->only(['name', 'avatar', 'age'])->withPostsOnly(['id', 'title', 'body'])->withCommentsOnly(['id', 'body']);
I know there is a way to make methods inside models that return these parts of data and then to use it same as above but shorter.
But is there any way to use something like getNameAttribute($value) for relations so I can say:
$user->only(['id', 'name', 'age', 'posts']);
And in posts value I need to have all posts and relationship data like comments and users that are connected to comments.
So basically in User model:
public function posts() {
return $this->hasMany('App/Post')->only('id', 'title', 'body', 'comments');
}
And inside Post model:
public function comments() {
return $this->hasMany('App/Comment')->only('id', 'body', 'user');
}
And inside Comment model:
public function comments() {
return $this->belongsTo('App/User')->only('id', 'name');
}
Thanks
You are probably overcomplicating it to be honest.
$user = User::where('username', request('username'))->first();
$user->load(['posts.comments']);
return response()->json($user);
This is a simplified version maybe but still should indicate you can just load relationships on models.

Laravel 5.3 adding data into two tables from the same form

I am quite new to Laravel and I would like to ask if there is any possible way to store only 2 form fields inside a table while all of the data are stored inside one table at the same time.
For instance I have users table where is store the data from my form .
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
"role" => $data["role"],
]);
}
And this is my route.
Route::get('users/create', ["uses" => "UsersController#create"]);
I have tried this and it is not inserting the data into the second table.
protected function create2(array $data)
{
return User::create2([
"name" =>$data["name"],
"role" => $data["role"],
]);
}
Route:
Route::get('users/create2', ["uses" => "UsersController#create2"]);
What would I have to do to store at the same time only the role lets say and the name into a different table ?
UserController--> https://pastebin.com/8yjtLVar
RegisterController --> https://pastebin.com/DTiRJu3m
In the function create2,write:
protected function create2(array $data)
{
return User::create([
"name" =>$data["name"],
"role" => $data["role"],
]);
}
In the create2 function,write:
protected function create2(array $data)
{
return Userrole::create([
"name" =>$data["name"],
"role" => $data["role"],
]);
}
Make sure that Userrole model is created for usersrole table in the database.

laravel one-to-one unique constrait

I have a one-to-one unidirectional relation.
class User extends Model
{
public $timestamps = false;
public function profile()
{
return $this->hasOne(Profile::class);
}
}
class Profile extends Model
{
public $timestamps = false;
}
I want to create a user with a single profile:
$user = User::firstOrCreate([
'name' => 'John',
'email' => 'john#email.com'
]);
$profile = new Profile([
'age' => 'age',
'sex' => 'sex'
]);
$user->profile()->save($profile);
Running this command multiple times creates one user with multiple profiles without a exception/warning that User model will have multiple relations.
How can I create a constraint or ensure that User will have only one profile?
Update:
Because my command can run multiple times, unique on profile_id will throw an exception which is not ideal in my case. I end up doing something like this:
$user = User::firstOrCreate([
'name' => 'John',
'email' => 'john#email.com'
]);
$user->profile()->firstOrCreate([
'age' => 'age',
'sex' => 'sex'
]);
You can:
Set user_id as unique()
Manually check if profile already exists $user->profile()->isEmpty()
Use updateOrCreate() or firstOrCreate() methods.

Laravel, get id from newly created object

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";
}

Resources