How to get inserted row id in laravel? - laravel-5.4

We created a school table with id = 56.
then We created a activity table with id = 1.
Now How to save school_id = 56 in activity table.
I have a problem. How do I get insert id from schools table?
public function store(Request $request)
{
if($request->ajax()) {
$activity = new Activity();
$activity->cluster_id = $request->cluster_id;
$activity->group_id = $request->group_id;
$activity->school_id = School::id;
$activity->save();
return response()->json(['data' => $request->all(), 'id' => $activity->school->id]);
}
}
Database
public function up()
{
Schema::create('activities', function (Blueprint $table) {
$table->increments('id');
$table->integer('school_id')->unsigned();
$table->integer('cluster_id')->unsigned();
$table->integer('group_id')->unsigned();
$table->timestamps();
$table->foreign('school_id')->references('id')->on('schools');
$table->foreign('cluster_id')->references('id')->on('clusters');
$table->foreign('group_id')->references('id')->on('groups');
});
}
Model
class Activity extends Model
{
public function school()
{
return $this->belongsTo(SchoolsList::class);
}
}

Suppose your School Model save method looks like this :
$school = new School;
$school->title = 'Baghoon High School';
$school->location= 'Bangladesh';
$school->save();
then you want to run this code
if($request->ajax()) {
$activity = new Activity();
$activity->school_id = $school->id;
$activity->save();
return response()->json(['data' => $request->all(), 'id' => $school->id]);
}

Related

How to update a pivot table with multiple relations using Eloquent in laravel 8

I am working with laravel 8, it causes me the doubt how to update that data from user the pivot table
class User extends Authenticatable
{
public function roles()
{
return $this->belongsToMany(Role::class,'contracts');
}
public function offices()
{
return $this->belongsToMany(Office::class,'contracts');
}
public function documents(){
return $this->hasMany(Document::class,'creator_id');
}
}
There is a many-to-many relationship between roles and offices that provides me with a pivot table like so:
Table Name: contracts
Colums:
id
user_id
office_id
role_id.
And I tried this way but it only updates me the user data but in the pivot table it does nothing
public function update($id, UpdateUserRequest $request)
{
if (empty($id)) {
return $this->sendError('User not found');
}
$userUpdate = User::find($id);
$userUpdate->name = $request->name;
$userUpdate->document = $request->document;
$userUpdate->email = $request->email;
if ($request->password != null) {
$userUpdate->password = bcrypt($request->password);
} else {
$userUpdate->password = $userUpdate->password;
}
$userUpdate->save();
$userUpdate->offices()->updateExistingPivot($request->office_id,['role_id'=>$request- >role_id]);
return $this->sendResponse($userUpdate->toArray(), 'User updated successfully');
}
I need to solve that problem.

Laravel 5.8 show data of the another table like join

I need how to show data in another table like MySQL join or something like that
MySQL example
My Code
Model usuarios
class Usuario extends Model {
protected $table = 'usuarios';
protected $primaryKey = 'idusuarios';
protected $filliable = [
'cedula', 'nombre', 'tele1', 'tele2', 'correo', 'direccion',
'user_name', 'user_pass', 'fecha_ingreso', 'usu_idrol'
];
public function Usuario() {
return $this->hasOne('app\Roles','idrole','usu_idrol','desc_rol');
}
const CREATED_AT = NULL;
const UPDATED_AT = NULL;
}
Model Roles
class Roles extends Model {
protected $table ='roles';
protected $primarykey = 'idrole';
protected $filliable = ['desc_rol'];
public function Roles() {
return $this->belongsTo('app\Usuario', 'usu_idrol', 'idrole');
}
}
Controller usuarios
public function index(Request $request) {
if (!$request->ajax()) return redirect('/');
$usuarios = Usuario::all();
return $usuarios;
}
View usuarios
that's what I need
Try this in the controller that is returning data to your vue instance
//get all the users from the database (in your controller)
//you need to create a new array so as to easily map the role in the returned results
return Usuario::with('Usuario')->get()->map(function($role) {
return [
'field1' => $role->field1,
'field2' => $role->field2,
'field3' => $role->field3,
'field4' => $role->field4,
'field5' => $role->field5,
'rol' => $role->Usuario->desc_role
];
});

How to get Sum from relationship in laravel

//Client Model
protected $fillable = [
'client_name', 'plan_id', 'client_type'
];
public function plan(){
return $this->belongsTo(Plan::class, 'plan_id', 'id');
}
// Plan Model
protected $fillable = [
'price'
];
public function clients()
{
return $this->hasMany(Client::class);
}
I want to get total price of all clients where client_type = something
I would do it like this:
function getClientTypeTotal($clientType)
{
return Client::where('client_type', $clientType)->get()->sum(function ($client) {
return $client->plan->price;
})
}

on delete cascade laravel

Morning everyone,
I have foreign keys set to on delete cascade in laravel 5 and mysql on a couple of tables where the existence of a employee depends on the existence of the country he was born in.
$table->foreign('id_estado_municipio')
->references('id_estado_municipio')
->on('cat_municipios')
->onDelete('cascade')
->onUpdate('cascade');
Problem is when I delete the country, the employee that must get erased along with it, gets erased from the database, but the employee's record keeps on showing at the index view.
Have tried setting engine to InnoDB in the config file, model observers to delete dependents but still can't figure out how to make it work.
Hopefully someone can give some light. It would be very much appreciate it.
Here you are my models and modelcontrollers
class Municipio extends Model
{
//
protected $table = 'cat_municipios';
protected $primaryKey = 'id_estado_municipio';
...
public function trabajadores()
{
return $this->hasMany(Trabajador::class,'id_trabajador');
}
protected static function boot() {
parent::boot();
static::deleting(function($municipio) {
// delete related stuff ;)
$municipio -> trabajadores() -> delete();
});
}
class MunicipioController extends Controller
{
...
public function destroy($id)
{
//
$municipio = Municipio::findOrFail($id);
$municipio -> trabajadores() -> delete();
$destruido = Municipio::destroy($id);
if($destruido)
return redirect()->route('Municipio.index')->with('info','Municipio eliminado con éxito.');
else
return redirect()->route('Municipio.index')->with('error','Imposible borrar Municipio.');
}
}
////////////////////////////////////////
class Trabajador extends Model
{
//
protected $table = 'trabajadors';
protected $primaryKey = 'id_trabajador';
...
public function municipio()
{
return $this->belongsTo(Municipio::class,'id_estado_municipio');
}
...
}
class TrabajadorController extends Controller
{
public function index()
{
//
$criterio = \Request::get('search'); //<-- we use global request to get the param of URI
$estadosciviles = EstadoCivil::orderBy('id_estado_civil')->paginate(50);
$estados = Estado::orderBy('id_estado') -> paginate(50);
$municipios = Municipio::orderBy('id_estado_municipio')->paginate();
$religiones = Religion::orderBy('id_religion')->paginate();
$trabajadores = Trabajador::where('nombre', 'like', '%'.$criterio.'%')
->orwhere('id_trabajador',$criterio)
->orwhere('a_paterno',$criterio)
->orwhere('a_materno',$criterio)
->orwhere('curp',$criterio)
->orwhere('rfc',$criterio)
->orwhere('seguro_social',$criterio)
->sortable()
->orderBy('id_trabajador')
->orderBy('nombre')
->paginate();
return view('Trabajador.index', array('trabajadores' => $trabajadores,'estadosciviles' => $estadosciviles,'estados' => $estados,'municipios' => $municipios,'religiones' => $religiones));
}
...
}

hasMany and belongsTo Laravel

I have 3 models. User, Notification and Lmo Notifications. The relation is a User hasMany Notifications and Notification has many LmoNotification.
to insert the notification and lmoNotification i created two models and controllers and they have separate database tables.
My problem is when i enter notifications into the database, it inserts data without any problem with user_id as the foreign key. But next when i try to enter the lmonotification, it gives an error.
Notification Model:
class Notification extends Model
{
protected $table = "notifications";
protected $fillable = [
'unit_code', 'unit_name', 'project_title', 'project_ref_number', 'storage_location', 'keeper_name', 'user_id',
];
public function user(){
return $this->belongsTo('App\User');
}
}
LmoNotification Model
class AddLmoNotification extends Model
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table = "lmo_notifications";
protected $fillable = [
'lmo_name', 'lmo_risk_level', 'lmo_quantity', 'lmo_volume', 'notification_id',
];
public function notification(){
return $this->belongsTo('App\Notification');
}
}
Notification controller to create the notification
public function create(Request $request)
{
$notification = Notification::create([
'unit_code'=>$request->unit_code,
'unit_name'=>$request->unit_name,
'project_title'=>$request->project_title,
'project_ref_number'=>$request->project_ref_number,
'storage_location'=>$request->storage_location,
'keeper_name'=>$request->keeper_name,
'user_id'=>Auth::user()->id
]);
return redirect()-> route('show.lmo_form', $notification->id);
// return view('ApplicationForms.notifi', $notification);
}
Lmonotification controller
$notification = new Notification;
/*this loop is because im adding rows dynamically to the table*/
$count = count($request->input('lmo_name'));
for ($i=0; $i<$count; $i++){
$data = AddLmoNotification::create([
'lmo_name'=>$request->lmo_name[$i],
'lmo_risk_level'=>$request->lmo_risk_level[$i],
'lmo_quantity'=>$request->lmo_quantity[$i],
'lmo_volume'=>$request->lmo_volume[$i],
'notification_id'=>$notification->id
]);
return response($data);
}
//return response($notification);
return redirect()->route('show.go_to_notification');
}
web.php
Route::prefix('notification')->group(function(){
/*show notification main page*/
Route::get('/', 'HomeController#getNotificationPage')->name('show.go_to_notification');
/*route to lmo_notification_form*/
Route::get('/personal_information_notification_form', 'HomeController#getNotificationForm');
/*route to biohazardous material notification form*/
Route::get('/biohazardous_material_notification_form', 'HomeController#getotherNotificationForm')->name('show.biohazardous_material_notification_form');
/*submit lmo notification route*/
Route::post('/personal_information_notification_form/submit', 'NotificationController#create')->name('submit.personal_Info_Notification');
/*Rtoute to lmo form*/
Route::get('/personal_information_notification_form/add_lmo/{notification_id}', 'HomeController#getlmoNotificationForm')->name('show.lmo_form');
/*Route to submit lmo list for notification*/
Route::post('/personal_information_notification_form/add_lmo', 'LmoNotificationController#create')->name('submit.lmo_list');
});
Notification table
Schema::create('notifications', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade')->onUpdate('cascade');
$table->string('unit_code')->nullable();
$table->string('unit_name')->nullable();
$table->string('project_title')->nullable();
$table->string('project_ref_number')->nullable();
$table->string('storage_location');
$table->string('keeper_name');
$table->timestamps();
});
Lmo Notification table
public function up()
{
Schema::create('lmo_notifications', function (Blueprint $table) {
$table->increments('id');
$table->integer('notification_id')->unsigned();
$table->foreign('notification_id')->references('id')->on('notifications')->onDelete('cascade')->onUpdate('cascade');
$table->string('lmo_name');
$table->string('lmo_risk_level');
$table->string('lmo_quantity');
$table->string('lmo_volume');
$table->timestamps();
});
}
the notification table contains some personal details fields and the lmonotification contains list of products.
the error message says that
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'notification_id' cannot be null (SQL: insert into lmo_notifications (lmo_name, lmo_risk_level, lmo_quantity, lmo_volume, notification_id, updated_at, created_at) values (asd, medium, 2, 2, , 2017-05-09 22:35:15, 2017-05-09 22:35:15))
Please help.
There is nothing wrong with your relations setup. The problem starts where you set the notification_id of your new AddLmoNotification off of a model you instantiated with:
$notification = new Notification;
Note that as long as $notification is not persisted to database with:
$notification->save()
that notification will not have an ID assigned to it by the database, and thus, accessing its id attribute returns null. So you'll have to save the $notification model first, before creating any models that rely on its id attribute for their foreign-key fields.