delete data based on company_id and year from database in laravel - php

I want to delete data based on company_id and year from my database.
sample data content
my model in App\Models, I've added the company_id and year to be for the primary key
class CompanyMasterCuti extends Model
{
use HasFactory;
protected $table = 'company_master_cuti';
protected $fillable = [
'company_id', 'year', 'cuti', 'created', 'created_by', 'modified', 'modified_by',
];
protected $guarded = [];
protected $keyType = 'string';
public $timestamps = false;
protected $primaryKey = ['company_id', 'year'];
public $incrementing = false;
public function company() {
return $this->belongsTo('App\Models\Company', 'company_id', 'id');
}
}
my code in controller
public function delete_master_cuti($company_id, $year) {
$master_cuti = CompanyMasterCuti::where('company_id', $company_id)->where('year', $year)->first();
$master_cuti->delete();
toast('Success', 'success');
return redirect()->route('master-cuti.index');
}
index.blade.php, in this code I've added the requested company_id and year to delete the data, but this method still doesn't work
<a href="javascript:void(0)" onclick="$('#master_cuti_ids').val($(this).data('company_id','year')); $('#deleteModalBu').modal('show');">
<li class="badge-circle badge-circle-light-secondary bx bxs-trash font-medium-1 text-danger my-1"></i>
</a>
form action to delete function delete data in index.blade.php
<form id="form-edit" action="{{ route('delete_master_cuti', [$m_cuti->company_id, $m_cuti->year] ) }}" method="POST">
#csrf
<div class="modal-body">
<input type="hidden" id="company_id" name="company_id">
<input type="hidden" id="year" name="year">
<div class="row no-gutters">
<div class="col-md-6">
<button type="button" class="btn btn-light-secondary" data-dismiss="modal"
style="width: 100%;">
<i class="bx bx-x d-block d-sm-none"></i>
<span class="d-none d-sm-block">Cancel</span>
</button>
</div>
<div class="col-md-6">
<button type="submit" class="btn btn-danger ml-1" style="width: 100%">
<i class="bx bx-check d-block d-sm-none"></i>
<span class="d-none d-sm-block">Delete</span>
</button>
</div>
</div>
</div>
</form>
my route
Route::post('delete_master_cuti/{company_id}/{year}', [CompanyMasterCutiController::class, 'delete_master_cuti'])->name('delete_master_cuti');
I get error: Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST. Please help me

Related

Laravel 8 Undefined variable: comments

I am trying to build a commenting system where users are able to leave comments behind on posts.
I can save and display the post and on a page i display all post I have a form where users can leave comments behind. I am able to save the comments in the database but when I try to show the comments I get this error Undefined variable: comments (View: /var/www/resources/views/projects/comment.blade.php).
My files: Comment Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Comment extends Model
{
use HasFactory, SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['user_id', 'post_id', 'parent_id', 'description'];
/**
* Write Your Code..
*
* #return string
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Write Your Code..
*
* #return string
*/
public function replies()
{
return $this->hasMany(Comment::class, 'parent_id');
}
}
Post Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class post extends Model
{
use HasFactory, SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [ 'titre',
'description',
'image',
'tag',
'video',
'status',
'user_id'];
/**
* Write Your Code..
*
* #return string
*/
public function comments()
{
return $this->hasMany(Comment::class)->whereNull('parent_id');
}
}
My CommentController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comment;
class CommentController extends Controller
{
/**
* Write Your Code..
*
* #return string
*/
public function store(Request $request)
{
$input = $request->all();
$request->validate([
'body'=>'required',
]);
$input['user_id'] = auth()->user()->id;
Comment::create($input);
return back();
}
}
post display controller
public function post_display()
{
if(Auth::id()){
$userid=Auth::user()->id;
$profile=user::find($userid);
$post=post::where('user_id',$userid)->get();
return view('user.post_display',compact('post','profile'));
}
else{
return redirect()->back();
}
}
My post display view
#include('user.head')
#include('user.create_post')
<section class="ftco-section">
<div class="container" align="center" >
#foreach($post as $posts)
#if(session()->has('message2'))
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">
x
</button>
{{session()->get('message2')}}
</div>
#endif
<div class="col-md-8 col-xl-6 middle-wrapper">
<div class="row">
<div class="col-md-12 grid-margin">
<div class="card rounded">
<div class="card-header">
<div class="d-flex align-items-center justify-content-between">
<div class="d-flex align-items-center">
<img class="img-xs rounded-circle" src="https://bootdey.com/img/Content/avatar/avatar6.png" alt="">
<div class="ml-2">
<p>{{$profile->username}}</p>
<p class="tx-11 text-muted">{{$posts->created_at}}</p>
</div>
</div>
<div class="dropdown">
#include('user.update_post')
</div>
</div>
</div>
<div class="card-body">
<h5> {{$posts->tag}}
</h5>
<h4 class="mb-3 tx-14"> {{$posts->status}}</h4>
<p class="mb-3 tx-14"> {{$posts->description}}</p>
<img class="img-fluid" src="postimage/{{$posts->image}}" alt="">
</div>
<div class="card-footer">
<div class="d-flex post-actions">
<a href="javascript:;" class="d-flex align-items-center text-muted mr-4">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart icon-md">
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
</svg>
<p class="d-none d-md-block ml-2">Like</p>
</a>
<h4>Display Comments</h4>
<hr />
#include('user.comment', ['comments' => $posts->comments, 'post_id' => $posts->id])
<h4>Add comment</h4>
<form method="post" action="{{ route('comments.store') }}">
#csrf
<div class="form-group">
<textarea class="form-control" name="description"></textarea>
<input type="hidden" name="post_id" value="{{ $posts->id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add Comment" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
</div>
</section>
#include('user.footer')
<!-- loader -->
<div id="ftco-loader" class="show fullscreen"><svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#F96D00"/></svg></div>
#include('user.script')
</body>
my comment dispaly view
#foreach($comments as $comments)
<div class="display-comment" #if($comments->parent_id != null) style="margin-left:40px;" #endif>
<strong>{{ $comments->user->name }}</strong>
<p>{{ $comments->body }}</p>
<form method="post" action="{{ route('comments.store') }}">
#csrf
<div class="form-group">
<input type="text" name="body" class="form-control" />
<input type="hidden" name="post_id" value="{{ $post_id }}" />
<input type="hidden" name="parent_id" value="{{ $comments->id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Reply" />
</div>
<hr />
</form>
#include('user.comment', ['comments' => $comments->replies])
</div>
#endforeach
My comment routes:
Route::post('comment',[CommentController::class,'comment'])->name('comments.store');
whene i try to create a new laravel project and put nothing other then post and comment it work.so i don't know where is the error.

Slow simple eloquent queries

Im new to laravel eloquent and i want to know if that loading times are normally with only five entries
Even a simple select all query has ~720 ms specially on edit button that is first photo (modal) the data comes after one second that is noticeable,
Im using Livewire i dont know if affect that too much
The main question that affects extra loading time is how to have access (Aggregate) on child table that counts only the sum of the services, i wrote a simple count on my html {{ $customer->services->count()}} table as you can see runs on each row that is wrong because adds extra loading time.
On php i make something like :
$sql = "SELECT name,vat,id";
$sql .= " ,(select sum(taskcharges) from charges where charges.customers_id=customers.id) as taskcharges_sum";
$sql .= " ,(select sum(payment) from charges where charges.customers_id=customers.id) as payment_sum";
$sql .= " ,(select sum(taskcharges-payment) from charges where charges.customers_id=customers.id) as balance_sum";
$sql .= " ,(select name WHERE customers.id=$id) ";
$sql .= " FROM customers ";
I want to have access from Customers on specific child(services) columns to make functions like max,sum,count the tables are binded on model so i want to avoid extra code of join queries
plus as you can see on sorting the "services" isnt column of Customers table so they dont recognize the column services on customers table, if i had something like "select count(services) as servicecount then i will able to recognize the sorting as new column of the table customers
Above you can see my code:
customers/show.blade.php:
<div class="container">
<p>Sort column:{{$selectedItems}}</p>
<p>Selected Direction:{{$action}}</p>
<!-- Button trigger modal -->
<button wire:click.prevent="addNew" type="button" class="btn btn-primary">
Add New User
</button>
<!-- button triger Modal -->
<div class="modal fade" id="form" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Insert</h5>
<button type="button" wire:click.prevent="close"class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#livewire('customers.form')
</div>
</div>
</div>
</div>
<div class="modal fade" id="delete" tabindex="-1" role="dialog" aria-labelledby="delete" aria-hidden="true" wire:ignore>
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="delete">Delete</h5>
<button type="button" wire:click.prevent="close" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h3>Do you wish to continue?</h3>
</div>
<div class="modal-footer">
<button type="button" wire:click="close" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button wire:click="delete" class="btn btn-primary">Delete</button>
</div>
</div>
</div>
</div>
<h1 class="text-center">Customers {{count($customers)}}</h1>
<div>
<div class="w-full flex pb-10">
<div class="w-3/3 mx-1">
<input wire:model.debounce.300ms="search" type="text" class="form-control" placeholder="Search users...">
</div>
<div class="row mb-4">
<div class="col form-inline">
Per Page:
<select wire:model="perPage" class="form-control">
<option>5</option>
<option>10</option>
</select>
</div>
</div>
</div>
<table class="table-auto w-full mb-6">
<thead>
<tr>
<th wire:click="sortBy('id')" style="cursor: pointer;" class="px-4 py-2">ID
#include('layouts.partials.sort_icons',['field'=>'id'])
</th>
<th wire:click="sortBy('name')" style="cursor: pointer;" class="px-4 py-2">Name
#include('layouts.partials.sort_icons',['field'=>'id'])</th>
<th wire:click="sortBy('plate')" style="cursor: pointer;" class="px-4 py-2">Plate
#include('layouts.partials.sort_icons',['field'=>'id'])</th>
<th wire:click="sortBy('services')" style="cursor: pointer;" class="px-4 py-2">Services
#include('layouts.partials.sort_icons',['field'=>'services'])</th>
<th class="px-2 py-2">Action</th>
</tr>
</thead>
<tbody>
#foreach($customers as $customer)
<tr>
<td class="border px-4 py-2">{{ $customer->id }}</td>
<td class="border px-4 py-2">{{ $customer->name }}</td>
<td class="border px-4 py-2">{{ $customer->plate }}</td>
<td class="border px-4 py-2">{{ $customer->services->count()}}</td>
<td class="border px-2 py-2">
<button wire:click="selectItem({{$customer->id}},'update')" class="btn btn-info"><i class="fa fa-edit"></I></button></a>
<button wire:click="selectItem({{$customer->id}},'delete')" class="btn btn-danger"><i class="fa fa-trash"></I></button></a>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="paginate">{{$customers->links()}}</div>
</div>
</div>
customers/Show.php :
<?php
namespace App\Http\Livewire\Customers;
use App\Models\Customer;
use Livewire\Component;
use App\Page;
use Illuminate\Support\Str;
use App\Http\Livewire\Column;
use Livewire\WithPagination;
class Show extends Component
{
public $sortBy= 'name';
public $sortDirection = 'asc';
public $headers;
public $perPage ='5';
public $search;
public $action;
public $selectedItems;
public function sortBy($field){
if ($this->sortDirection =='asc'){
$this ->sortDirection ='desc';
}
else{
$this->sortDirection ='asc';
}
return $this ->sortBy = $field;
}
public function selectItem($itemId,$action){
$this->selectedItems=$itemId;
$this->action=$action;
if ($action=='delete'){
$this->dispatchBrowserEvent('show-deletemodal');
} else{
$this->emit('getcustomerID', $this->selectedItems);
$this->dispatchBrowserEvent('show-modal');
}
}
public function delete(){
Customer::destroy($this->selectedItems);
$this->dispatchBrowserEvent('hide-modal');
}
public function addNew()
{
$this->dispatchBrowserEvent('show-modal');
}
public function close()
{
$this->dispatchBrowserEvent('hide-modal');
}
protected $listeners = [
'deleteconfirmed'=>'$selectedItems',
'refreshParent'=>'$refresh'
];
public function render()
{
$customers = Customer::query()
->search($this->search)
->orderBy($this->sortBy,$this->sortDirection)
->paginate($this->perPage);
return view('livewire.customers.show',['customers'=>$customers
])
->extends('admin.dashboard')
->section('content');
}
}
customers/form.php :
<?php
namespace App\Http\Livewire\Customers;
use App\Models\Customer;
use Livewire\Component;
class Form extends Component
{
public $name ='';
public $plate = '';
public $customerId ;
protected $listeners = [
'getcustomerID'
];
protected function rules() {
return [
'name' => 'required',
'plate' => ['required', 'regex:/[A-Z]{3}\d{4}$/','unique:customers,plate,' . $this->customerId],
];
}
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
public function getcustomerID($customerId){
$this->customerId=$customerId;
$customer= customer::find ($this->customerId);
$this->name=$customer->name;
$this->plate= $customer->plate;
}
public function save()
{
$this->validate();
$data = [
'name' => $this->name,
'plate' => $this->plate,
];
if ($this->customerId){
customer::find ($this->customerId)->update($data);
session()->flash('message', 'User successfully updated.');
} else{
customer::create($data);
}
$this->emit('refreshParent');
$this->dispatchBrowserEvent('hide-modal');
$this ->ClearVars();
}
public function ClearVars(){
$this->name=null;
$this->plate=null;
}
public function render()
{
return view('livewire.customers.form');
}
}
Models/Customer.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Customer extends Model
{
use HasFactory;
protected $fillable = [
'name',
'plate'
];
public function services()
{
return $this->hasMany(Service::class);
}
public function parts()
{
return $this->hasMany(Part::class, 'customer_id');
}
public function scopeSearch($query , $val){
return $query
->where('name','like','%'.$val.'%')
->Orwhere('plate','like','%'.$val.'%');
}
public function user()
{
return $this->belongsTo(User::class);
}
}
Models/Services.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Service extends Model
{
protected $fillable = [
'service_type',
'km',
];
public function customer()
{
return $this->belongsTo(Customer::class);
}
public function parts()
{
return $this->hasMany(part::class);
}
}
It was so simple.. just added ->withCount('services') above of query
Still have that strange delay
Update :
The problem with slow response was that trying to retrieve data from remote sql server, I change to local and I have less than 100ms!

cant display all result from 2 table join with pivot table

I have managed to join between 2 tables by using 1 pivot table(I have to), but I cant loop my way to get all of joined result, Bellow are:
Models
App.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class App extends Model
{
protected $table = 'bas_app';
public $timestamps = false;
protected $fillable = ['id','app_name','app_type','description','menu_name','menu_url','menu_parent_id'];
public function roles()
{
return $this->belongsToMany(Role::class,'bas_role_app','app_id','role_id');
}
}
Role.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
//
protected $table = 'bas_role';
protected $fillable = ['name','remark'];
public function users()
{
return $this->belongsToMany('App\User','bas_user_role','role_id','user_id')
->withPivot('id');
}
public function apps()
{
// return $this->belongsToMany(App::class,'bas_role_app','role_id','app_id')
// ->withPivot('id','priv_access','priv_insert','priv_delete',
// 'priv_update','priv_export','priv_print','app_name');
return $this->belongsToMany(App::class,'bas_role_app','role_id','app_id');
}
}
RoleApp.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
class RoleApp extends Pivot
{
//
public $timestamps = false;
protected $table = 'bas_role_app';
protected $fillable = ['role_id','app_id','app_name'];
public function b_app() {
return $this->belongsToMany(App::class);
}
public function b_role() {
return $this->belongsToMany(Role::class);
}
}
Controller
RoleAppController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use Illuminate\Support\Facades\Route;
use App\User;
use App\Role;
use App\App;
use App\ActivityLog;
use App\RoleApp;
use Illuminate\Support\Facades\Input;
use DB;
class RoleAppController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function display(Request $request)
{
$routes = preg_match('/([a-z]*)#([a-z]*)/i', Route::currentRouteAction(), $matches);
$routes = $matches[0];
$action = $matches[2];
if (Auth::check()) {
DB::beginTransaction();
try {
$id = Auth::id();
$profile_data = User::find($id);
$RoleApp = Role::all();
//$RoleApp->apps;
// dd($RoleApp);
ActivityLog::create([
'inserted_date' => Carbon::now()->TimeZone('asia/jakarta'),
'username' => $profile_data->username,
'application' => $routes,
'creator' => "System",
'ip_user' => $request->ip(),
'action' => $action,
'description' => "admin is looking at the role and application management",
'user_agent' => $request->server('HTTP_USER_AGENT')
]);
DB::commit();
} catch (\Exception $ex) {
DB::rollback();
return response()->json(['error' => $ex->getMessage()], 500);
}
// return view('RoleApp', ['RoleApp' => $RoleApp]);
return view('RoleApp', ['RoleApp' => $RoleApp]);
} else {
return view("login");
}
}
}
View
RoleApp.blade.php
#extends('layouts.master')
#section('title','Display-RoleApp')
#section('content')
<div class="container mt-5">
<div class="row">
<div class="col-12">
#if($errors->any())
<div class="alert alert-danger alert-dismissible fade show" role="alert">
{{ implode(', ', $errors->all(':message')) }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
<div class="float-right mb-5">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalCenter">
Insert Role App
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Insert User</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="/roleapp/create" method="POST">
{{ csrf_field() }}
<div class="form-group">
<label for="role_name">role name:</label>
<input type="text" class="form-control" name="role_name">
</div>
<div class="form-group">
<label for="app_name">app name:</label>
<input type="text" class="form-control" name="app_name">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
<div class="table-responsive m-b-40">
<table id="roleapp-table" class="table table-striped">
<thead>
<tr>
<th scope="col">Role Name</th>
<th scope="col">App Name</th>
<th scope="col" class="text-center">Action</th>
<th scope="col" class="text-center">Action</th>
</tr>
</thead>
<tbody id="dynamic-row">
#foreach ($RoleApp->apps as $rp)
<tr>
<td>{{$RoleApp->name}}</td>
<td>{{$rp->app_name}}</td>
<td class="text-center">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_ubah_{{$rp->id}}">Edit</button>
</td>
<td class="text-center">
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#modal_hapus_{{$rp->id}}">Hapus</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
var row = 0;
$(document).ready(function() {
$('#user-table').DataTable({
select: true,
retrieve: true,
"order": [
[0, "desc"]
],
"lengthMenu": [
[20, 50, 100, 500, 1000, -1],
[20, 50, 100, 500, 1000, "All"]
],
"language": {
"paginate": {
"next": ">",
"previous": "<"
}
}
});
});
$('#user-table thead tr').clone(true).appendTo('#user-table thead');
$('#user-table thead tr:eq(1) th').each(function(i) {
if (row < 7) {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
} else {
$(this).html('');
}
row++;
$('input', this).on('keyup change', function() {
if (table.column(i).search() !== this.value) {
table
.column(i)
.search(this.value)
.draw();
}
});
});
</script>
#endsection
Any suggestion? I have tried various way and its still not working. I suspect that something is wrong in
$RoleApp = Role::all();
or
#foreach ($RoleApp->apps as $rp)
<tr>
<td>{{$RoleApp->name}}</td>
<td>{{$rp->app_name}}</td>
<td class="text-center">
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#modal_ubah_{{$rp->id}}">Edit</button>
</td>
<td class="text-center">
<button type="button" class="btn btn-danger" data-toggle="modal" data-target="#modal_hapus_{{$rp->id}}">Hapus</button>
</td>
</tr>
#endforeach
if I try it with $RoleApp = Role::find(2); it will still work, but when i use get or all, it wont work.
without eager loading.
$roles = Role::all();
with eager loading
$roles = Role::with('apps')->get();
$roles is a collection of model instances of Role Model. You can't access a property or relation of a model, on a collection. That is the reason it works when you use find(given model instance), and doesn't work for all or get(give collection).
You need to iterate over the collection and then access the relation like this.
foreach($roles as $role){
// name of each role.
$role->name;
foreach($role->apps as $app){
// name of each app associated with the $role.
$app->name;
}
}

Laravel Update user's data

I'm building a traveling app and the user has the possibility to edit their own departure date in case of a misplacement. At the moment, the user can edit the departure date from everyone. While it only should edit their own. Everything is working, but the update function where it should look for Auth::user();. Any idea how I should make this?
Here is the code:-
DepartureController.php
public function edit(LocationUser $LocationUsers)
{
return view('departure.edit', compact('LocationUsers'));
}
public function update(Request $request, LocationUser)
{
$LocationUsers = Auth::user();
$LocationUsers->update($request->all());
return redirect()->route('home', $LocationUsers)
->withSuccess('Departure updated!');
}
The web.php
//Backend Departure date
Route::get('/departure/create', 'DepartureController#create')->name('departure.create');
Route::post('/departure/create', 'DepartureController#store')->name('departure.store');
Route::get('/departure/edit/{LocationUsers}', 'DepartureController#edit')->name('departure.edit{id}');
Route::patch('/departure/edit/{LocationUsers}', 'DepartureController#update')->name('departure.update');
The edit.blade.php
<div class="container-fluid">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card card-default">
<div class="card-header">
{{$LocationUsers->departure_date}}
Update my departure
</div>
<div class="card-body">
#if (session('success'))
<div class="alert alert-dismissible alert-success">
{{ session('success') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{route('departure.update', $LocationUsers)}}">
{!!csrf_field().method_field('patch')!!}
<div class="form-group"> <!-- Date input -->
<label class="control-label" for="departure_date"></label>
Date
<input class="form-control" id="departure_date" name="departure_date"
placeholder="DD/MM/YYYY" type="text"/>
</div>
<input type="submit" class="btn btn-primary" value="Update departure">
</form>
</div>
</div>
</div>
</div>
</div>
The User model
public function daysUntilDeparture()
{
if ($this->location()->count() < 1) {
return "No departure date has been given";
}
$location = $this->location[0];
$userLocation = LocationUser::where('user_id', $this->id)
->where('location_id', $location->id)
->first();
$departure_date = $userLocation->departure_date;
return $departure_date->diffInDays(Carbon::now());
}
The LocationUser model
<?php
namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class LocationUser extends Model
{
const DATE_FORMAT = 'd-m-Y';
protected $fillable = ['departure_date', 'user_id'];
protected $dates = ['departure_date'];
protected $table = 'location_users';
public function user() {
return $this->belongsTo('\App\User', 'id', 'user_id');
}
public function location() {
return $this->hasOne('\App\Location', 'id', 'location_id');
}
public function setDepartureDateAttribute($date)
{
$this->attributes['departure_date'] = Carbon::createFromFormat(self::DATE_FORMAT, $date);
}
}
You can use
public function update(Request $request)
{
$date = Carbon::parse($request->departure_date);
$LocationUsers = LocationUser::where('user_id', Auth::id())->update(['departure_date' => $date]);
if($LocationUsers){
return redirect()->route('home', $LocationUsers)->withSuccess('Departure updated!');
}
}

Trying to add data to database, but it's coming in as Null

I'm trying to add 2 fields of input through a modal, but once I hit submit I get an error message saying
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'Flag_Reason' cannot be null (SQL: insert into `Flagged` (`Flag_Reason`, `Other_Comments`) values (, ))
Here's some of my code pertaining to the issue.
Resource & Flag Models
class Resource extends Model
{
protected $table = 'Resources';
protected $primaryKey = 'Resource_ID';
public $timestamps = false;
protected $fillable = [
'Name',
'Description',
'Misc_Info'
];
protected $guarded = [];
/** A resource can have many locations */
public function locations()
{
return $this->belongsToMany('App\Models\Location', 'ResourceLocation', 'Location_ID', 'Resource_ID');
}
public function flag ()
{
return $this->hasMany('App\Models\Flagged');
}
class Flagged extends Model
{
protected $table = 'Flagged';
protected $primaryKey = 'Flag_ID';
public $timestamps = false;
protected $fillable = [
'Flag_Reason',
'Other_Comments',
];
protected $guarded = [];
}
Resource View (modal is triggered in this view)
<table class=" display table table-hover table-bordered" , id="resource">
<thead>
<th>Name</th>
<th>Description</th>
<th>Address</th>
</thead>
<tbody>
#foreach($resources as $resource) #foreach ($resource->locations as $location)
<tr>
<td> <a class="btn btn-small btn-default" style="float:right; margin-right:5px;" href="{{ URL::to('resource/addToCart/' .$resource->Resource_ID) }}">+</a> {{ $resource->Name }}</td>
<td>{{ $resource->Description }}</td>
<td>{{ $location->Address }}</td>
<td>
<button type="button" id="submitFlag" class=" msgBtn btn btn-default" style=" display:inline; margin-right:auto;">Flag
</button>
</td>
</tr>
#endforeach #endforeach
</tbody>
</table>
Modal
<div class="modal fade" id="flagResource" tabindex="-1" role="dialog" aria-labelledby="flagModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="flagResourceLabel" style="text-align:center;"> Flagged
</h4>
</div>
<div class="modal-body">
{!! Form::open(array('url'=>'flags', 'class'=>'form', 'method'=>'POST')) !!}
<div class="form-group">
<label for="reason" class="control-label">Reason for Flagging:</label>
{!! Form::text('reason', null, array('class'=> 'form-control', 'placeholder'=>'Reason')) !!}
</div>
<div class="form-group">
<label for="comments" class="control-label">Other Comments:</label>
{!! Form::text('comments', null, array('class'=> 'form-control', 'placeholder'=>'Comments')) !!}
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<span class="pull-right">
<button type="button" class="btn btn-primary" style="margin-left:5px;">Submit</button>
</span>
</div>
{!! Form::close() !!}
</div>
</div>
</div>
<script>
$('#flagResource').on('show.bs.modal', function(e) {
var submitFlag = $(e.relatedTarget);
var resourceName = submitFlag.data('resource-name');
var resourceId = submitFlag.data('resource-id');
var modal = $(this);
modal.find('.modal-title').text(resourceName);
});
</script>
Flag Controller
public function addFlag($id)
{
$flag = Flagged::create(Request::only(
'Flag_Reason',
'Other_Comments' ));
$flag->save(); \Session::flash('flash_message', 'Flagged!');
return back();
}
Once I input a reason and comments for the flag, I get the above message. What am I doing wrong here? Thanks in advance!
EDIT ROUTES
Route::get('flags', 'FlagsController#index');
Route::post('resource', ['as' => 'resource', 'uses'=>'FlagsController#postFlag']);
Route::get('flags/edit/{Resource_ID}', 'FlagsController#editResource');
Route::patch('flags/edit/{Resource_ID}', 'FlagsController#updateResource');
Route::get('setflag/{Resource_ID}', 'FlagsController#addFlag');
Route::get('pages/editresources/rmflag/{Resource_ID}', 'FlagsController#removeFlag');
Route::get('pages/editresources/rmdelete/{Resource_ID}', 'FlagsController#removeDelete');
Route::get('setdelete/{Resource_ID}', 'FlagsController#addDelete');
Fixed it by changing this in my controller :
$flag = Flagged::create(Request::only(
'Flag_Reason',
'Other_Comments' ));
to this:
public function postFlag()
{
$flag = Flagged::create([
'Flag_Reason' => Input::get('reason'),
'Other_Comments' =>Input::get('comments')]);
$flag->save();
\Session::flash('flash_message', 'Flagged!');
return redirect('resource');
}

Categories