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!');
}
}
Related
I am trying to create a 'favouriting' system where i need to check if the 'dish' is already favourited or not. I am having some troubles figuring out how to do so.
I am on my 'Resturant' show page, which contains the following:
Resturant Controller:
public function show($id)
{
$resturant = Resturant::find($id);
$favourites = Favourite::all();
return view('resturants.resturant_show')->with('resturant', $resturant)->with('dishes', Dish::all())
->with('favourites', Favourite::all());
}
Resturant_show:
<div class="row row-cols-1 row-cols-md-3 g-4 m-3">
#foreach ($dishes as $dish)
#if ($resturant->id == $dish->resturant_id)
<div class="col">
<div class="card h-100">
//accessing $dish->id etc here, taken out to reduce snippet size
#foreach ($favourites as $favourite)
#if ($dish->id == $favourite->user_id)
<form method="POST" action='{{ url("favourite/$favourite->id") }}'>
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button
class="btn btn-outline-danger
type="submit" value="Delete"></3</button>
</form>
#else
<form method="POST" action='{{ url("favourite/$favourite->id") }}'>
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button
class="btn btn-outline-danger"
type="submit" value="Delete"><3</button>
</form>
#endif
#endforeach
<button type="button"
class="btn btn-outline-primary">
${{ $dish->price }} <span
class="rounded-pill bg-danger">Discount
#%</span>
</button>
</div>
</div>
</div>
#endif
#endforeach
</div>
#foreach ($favourites as $favourite)
#if ($dish->id == $favourite->user_id)
This is where I am looking to only display a single button (currently one foreach as I don't know how to find the right favourite data).
My relationships look like such:
Favourite
//Relationship with user
function user() {
return $this->belongsTo('App\Models\User', 'user_id');
}
//Relationship with dish
function dish() {
return $this->belongsTo('App\Models\Dish', 'dish_id');
}
Dish
//Relationship with resturant
function resturant() {
return $this->belongsTo('App\Models\Resturant', 'resturant_id');
}
//Relationship with favourite
function favourite() {
return $this->hasMany('App\Models\Favourite', 'favourite_id');
}
Resturant
//Relationship with user
function user() {
return $this->belongsTo('App\Models\User', 'user_id');
}
//Relationship with dish
function dish() {
return $this->hasMany('App\Models\Dish', 'dish_id');
}
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
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!
I am having a little problem here. I am trying to put an image in my User Profile. The image is saved in the database and no errors are shown up, but I never see the default image that I gave to it. It says that it's there but The place for the pic stays empty.
This is what I've got for now:
UserController.php
<?php
namespace app\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
// namespace App\Http\Controllers\Controller;
// use App\Http\Requests\Request;
// use Illuminate\Http\Request;
class UserController extends Controller
{
public function profile()
{
$user = Auth::user();
return view('profile',compact('user',$user));
}
public function update_avatar(Request $request){
$request->validate([
'avatar' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user = Auth::user();
$avatarName = $user->id.'_avatar'.time().'.'.request()->avatar->getClientOriginalExtension();
$request->avatar->storeAs('avatars',$avatarName);
$user->avatar = $avatarName;
$user->save();
return back()
->with('success','You have successfully upload image.');
}
/** Return view to upload file */
public function uploadFile(){
return view('uploadfile');
}
/** Example of File Upload */
public function uploadFilePost(Request $request){
$request->validate([
'fileToUpload' => 'required|file|max:1024',
]);
$request->fileToUpload->store('logos');
return back()
->with('success','You have successfully upload image.');
}
}
profile.blade.pbp
<hidden='Illuminate\Support\Facades\Auth'>
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
#if ($message = Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{{ $message }}</strong>
</div>
#endif
#if (count($errors) > 0)
<div class="alert alert-danger">
<strong>Whoops!</strong> There were some problems with your input.<br><br>
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
</div>
<div class="row justify-content-center">
<div class="profile-header-container">
<div class="profile-header-img">
<img class="rounded-circle" width="150" height="150" src="/storage/avatars/{{ $user->avatar }}" />
<!-- badge -->
<div class="rank-label-container">
<span class="label label-default rank-label">{{$user->name}}</span>
</div>
</div>
</div>
</div>
<div class="row justify-content-center">
<form action="/profile" method="post" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input type="file" class="form-control-file" name="avatar" id="avatarFile" aria-describedby="fileHelp">
<small id="fileHelp" class="form-text text-muted">Please upload a valid image file. Size of image should not be more than 2MB.</small>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
#endsection
filesystems.php
'default' => env('FILESYSTEM_DRIVER', 'public'),
How can I make the default avatar visible?
Also, do you have any suggestions on how to put a watermark on the photos that will appear each time someone uploads photos?
Thanks in advance!
You can try this. First execute this command
php artisan storage:link
Then
<img class="rounded-circle" width="150" height="150" src="{{url('')}}/storage/avatars/{{ $user->avatar }}"/>
i cant seem to fix my issue when i delete a task it redirects me to dashboard i can see in controller it is currently redirecting to /dashboard page however when i try to fix this it just errors out :/ i want it to acheive the same result the create redirection does
public function createTaskPage(Request $request, $slug) {
$project = Project::where('slug', $slug)->firstOrFail();
// Validate it has a body.
$validate = validator(
$request->toArray(), [
'task' => 'required',
]);
if ($validate->fails()) {
return response()->json([], 400);
}
$tasks = new Task;
$tasks->project_id = $project->id;
$tasks->body = $request->task;
$tasksCreate = Auth::user()->tasks()->save($tasks);
//return response()->json([], 201);
return redirect()->to('/project/' . $project->slug);
}
public function doDeleteTask($id) {
try {
$tasks = Task::where('user_id', Auth::user()->id)->findOrFail($id);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $ex) {
return response()->json([], 404);
}
$tasks->delete();
//return response()->json([], 204);
return redirect()->to('/dashboard');
}
This is the Form where delete button is
<div class="col-md-3">
<div class="panel panel-default shadow">
<div class="panel-body">
<div class="row text-center">
<h4><strong>{{ str_limit(strip_tags($project->name), 20) }}</strong></h4>
<h5>{{ $project->created_at }}</h5>
</div>
<div class="row text-center" style="margin:5px;">
{{ ($project->description) }}
</div>
<div class="row text-center">
<form action="{{ url('/project/'.$project->id) }}" method="POST">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit" class="btn btn-link btn-sm" onclick="return ConfirmDelete(this)" style="margin:5px;"><i class="fa fa-ban fa-3x" aria-hidden="true"></i></button>
<i class="fa fa-arrow-circle-o-right fa-3x" aria-hidden="true"></i>
</form>
</div>
</div>
</div>
This is my Delete route & create route
Route::delete('/task/{id}', 'TaskController#doDeleteTask'); // Delete a task
Route::post('/project/{slug}/task', 'TaskController#createTaskPage')->name('task');
If you have a project relation defined in tasks, you can do this:
public function doDeleteTask($id) {
try {
$tasks = Task::where('user_id', Auth::user()->id)->findOrFail($id);
} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $ex) {
return response()->json([], 404);
}
$project = $tasks->project;
$tasks->delete();
return redirect()->to('/project/' . $project->slug);
}