I am working on a very simple project for my school assignment. So it's a house rent site. Everything seems fine but I want create an automatically invoice like "INV0001" but I don't know how to do that. Maybe you guys can help me fix my controller
This is my controller
public function storeSewa(Request $request){
if ($request->edit=='false') {
$newdata = new Sewa;
} else {
$newdata = Sewa::find($request->id);
if ($newdata) {
//
}else {
$newdata = new Sewa;}}
$newdata->invoice = 'INV/'//idk, how?
$newdata->penyewa_id = $request->penyewa_id;
$newdata->kamar_id = $request->kamar_id;
$newdata->tanggal_masuk = $request->tanggal_masuk;
$newdata->tanggal_keluar = $request->tanggal_keluar;
$newdata->durasi = $request->durasi;
$newdata->status = 'Belum Lunas';
$newdata->save();
if ($newdata) {
session()->flash('status', 'Task was successful!');
session()->flash('type', 'success');
return Redirect::route('account');
}
return 'false';
}
Well, I am very new to laravel, so is there anyone can help fix my problem in the easiest way?
if you are using database you can use sql auto increment, for this feature you have to have this line in your invoice models migration :
Schema::create('invoices', function (Blueprint $table) {
$table->Increments('id');
});
if you want your invoice numbers, not being like 1,2,3, ... you can use libraries like this:
https://github.com/oanhnn/laravel-fakeid
if you are using for test, you can use faker factory:
there is a tutorial here:
https://www.codermen.com/blog/75/how-to-use-faker-with-laravel-5-7-tutorial
Related
I made code like this in Models Number_npe:
public function nomor_akhir()
{
$query = DB::table('nomor_npe')
->select('*')
->orderBy('id','DESC')
->first();
return $query;
}
Then the Controllers:
public function nomor_npe_store(Request $req)
{
$tanggal_npe = $req->input('tanggal_npe');
$pesan = new Nomor_npe();
$check = $pesan->nomor_akhir();
if($check) {
$nomor_npe = $check->nomor_npe+1;
}else{
$nomor_npe = 1;
}
DB::table('nomor_npe')->insert([
'nomor_npe' => $nomor_npe,
'tanggal_npe' => $tanggal_npe
]);
return redirect('nomor_npe')->with('success','Nomor NPE berhasil ditambahkan');
}
The Add NPE Number display looks like this:
When I click Save, the number_npe has been successfully added automatically.
But I want to make when the year changes, the number_npe restarts automatically from 1 again ... Please help everyone who knows
I have to write this as an answer, but it is not 100% an answer to your code, these are just tips for you to have better code. (So if anyone sees this too, they are aware too)
First of all, avoid 100% writing code in other language than English, as we are following it (we do not speak your language) and we do not understand nearly anything unless we use a Translator...
So, if you are going to use Laravel, try to avoid using DB, when you can just use the Model (hopefully you have created it...).
So your class should look like this:
public function lastNumber()
{
return NomorNpe::orderByDesc('id')->first();
}
Then your controller should be like:
public function store(Request $request, NomorNpe $nomor_npe)
{
NomorNpe::create([
'nomor_npe' => $nomor_npe->lastNumber() ? $nomor_npe->lastNumber()->nomor_npe + 1 : 1,
'tanggal_npe' => $request->input('tanggal_npe')
]);
return redirect('nomor_npe')->with('success', 'Nomor NPE berhasil ditambahkan');
}
See how I reduced everything from 13 lines of code to 5 lines of code and is 100% readable... (Or 9 lines to 2)
Make sure to use what Laravel brings you as "default" for it, use Models not DB::table('xxx'), take advantage of Eloquent.
Use this code for starting the number from 1, when the year changed:
public function nomor_npe_store(Request $req) {
$tanggal_npe = $req->input('tanggal_npe');
//---Current Date
$date = date('Y-m-d', time());
//---NOMOR NPE
$nomor_npe = DB('number_npe')->whereYear('tanggal_npe', $date)->max('normor_npe');
if (!$nomor_npe) {
$nomor_npe = 1;
} else {
$nomor_npe++;
}
DB::table('nomor_npe')->insert([
'nomor_npe' => $nomor_npe,
'tanggal_npe' => $tanggal_npe
]);
return redirect('nomor_npe')->with('success','Nomor NPE berhasil ditambahkan');
}
I'm trying to update a row in mysql table. However, when I click the register button, it doesn't do anything. I'm using Laravel.
Here's my update function:
public function update(Request $request)
{
$idpawn = $request['idprestamo'];
$paynumber = $request['numeropago'];
$payqty = $request['payqty'];
$statuspawns = statuspawns::find($idpawn,$paynumber);
$updateqty = $statuspawns->totalpayment - $payqty;
if($updateqty == "0"){
$status = "Pay";
}
else{
$status = "Partial Payment";
}
$statuspawns->total = $updateqty;
$statuspawns->status = $status;
$statuspawns->save();
return redirect()->back();
}
Thanks for your help.
I think the problem might be that you need square brackets instead of parenthesis since it's an array. $request['idprestamo']
$request['numeropago']
$request['payqty']
I'd like to also add that you can do it this way also with a magic method...
$request->numeropago
You have to access the Request this way $request->input_name not this way $request('input_name') because it is a Laravel Data Collection
In the end of the day, your function will look like this:
public function update(Request $request)
{
$idpawn = $request->idprestamo;
$paynumber = $request->numeropago;
$payqty = $request->payqty;
$statuspawns = statuspawns::find($idpawn,$paynumber);
$updateqty = $statuspawns->totalpayment - $payqty;
if($updateqty == "0"){
$status = "Pay";
}
else{
$status = "Partial Payment";
}
$statuspawns->total = $updateqty;
$statuspawns->status = $status;
$statuspawns->save();
return redirect()->back();
}
UPDATE
In Laravel 5.7 you have to use the update() method instead of the save() method to update a row.
You are not retrieving the record correctly. you have to pass only id to find(). As you have passed two parameters.
change this statement to..
$statuspawns = statuspawns::find($idpawn,$paynumber);
To
$statuspawns = statuspawns::find($idpawn);
Now you can update the columns which you want to update.
I'm creating REST API with Laravel 5.6 (I have to say I'm new because I might have used the wrong terms. I'm sorry about that,I'm improving myself. I need to hear my faults :) )
I have one function for find nearby places in my controller
public function index(\Illuminate\Http\Request $request) {
if($request->has('party_category')){
$parties = Parties::where('party_category', $request->party_category)->get();//your new query here
}
else if($request->has('lat') && $request->has('long')){
$parties = Parties::whereRaw("ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))*6380 < 10");
}else {
$parties = Parties::all();
}
return Fractal::includes('places')->collection($parties,new PartyTransformer);
}
and I'm using this url for send current location but when I giving them , laravel showing to me all parties not nearby.I want to show nearby places
http://127.0.0.1:8000/api/parties?lat=37.043237&long=27.392445
but when I sending my parameter to url it showing
{"data":[]}
I can't show any nearby places
also in my database I'm keeping lat and long like this :
public function up()
{
Schema::create('parties', function (Blueprint $table) {
$table->increments('id');
$table->integer('places_id')->unsigned();
$table->string('slug');
$table->string('party_title');
$table->string('party_category');
$table->string('rating')->nullable();
$table->date('party_date');
$table->string("latitude")->nullable();
$table->string("longitude")->nullable();
$table->integer('fav_count')->nullable();
$table->longText('image_path');
$table->longText('party_desp');
$table->timestamps();
});
}
How can I show the nearby ones ?
I fixed , I hope it will help somebody
class PartiesController extends Controller
{
public function index(\Illuminate\Http\Request $request) {
if($request->has('lat') && $request->has('long')){
$lat = $request->lat;
$long = $request->long;
$parties=DB::select(DB::raw("SELECT *,111.045*DEGREES(ACOS(COS(RADIANS(':lat'))*COS(RADIANS(`latitude`))*COS(RADIANS(`longitude`) - RADIANS(':long'))+SIN(RADIANS(':lat'))*SIN(RADIANS(`latitude`)))) AS distance_in_km FROM parties ORDER BY distance_in_km asc LIMIT 0,5"), array(
'lat' => $lat,
'long' => $long
));
$hidacik = Parties::hydrate($parties);
return Fractal::includes('places')->collection($hidacik,new PartyTransformer);
}
else {
$parties = Parties::all();
}
return Fractal::includes('places')->collection($parties,new PartyTransformer);
}
}
In $parties = Parties::whereRaw("ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))*6380 < 10");
you are missing ->get(). you need to add get() in order to return a collection which you can then work with
//this returns a collection now since we added get()
$parties = Parties::whereRaw("ACOS(SIN(RADIANS('latitude'))*SIN(RADIANS($request->lat))+COS(RADIANS('latitude'))*COS(RADIANS($request->lat))*COS(RADIANS('longitude')-RADIANS($request->long)))*6380 < 10")->get();
I want to implement a system in my project that "alerts" users when there is a new comment on one of their posts.
I currently query all comments on the posts from the logged in user and put everything in an array and send it to my view.
Now my goal is to make an alert icon or something when there is a new item in this array. It doesn't have to be live with ajax just on page load is already good :)
So I've made a function in my UsersController where I get the comments here's my code
public function getProfileNotifications()
{
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
//comments
if (!empty($projects)) {
foreach ($projects as $project) {
$comments_collection[] = $project->comments;
}
}
if (!empty($comments_collection)) {
$comments = array_collapse($comments_collection);
foreach($comments as $com)
{
if ($com->from_user != Auth::user()->id) {
$ofdate = $com->created_at;
$commentdate = date("d M", strtotime($ofdate));
$comarr[] = array(
'date' => $ofdate,
$commentdate,User::find($com->from_user)->name,
User::find($com->from_user)->email,
Project::find($com->on_projects)->title,
$com->on_projects,
$com->body,
Project::find($com->on_projects)->file_name,
User::find($com->from_user)->file_name
);
}
}
} else {
$comarr = "";
}
}
Is there a way I can check on page load if there are new items in the array? Like keep a count and then do a new count and subtract the previous count from the new one?
Is this even a good way to apprach this?
Many thanks in advance! Any help is appreciated.
EDIT
so I added a field unread to my table and I try to count the number of unreads in my comments array like this:
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
//comments
if (!empty($projects)) {
foreach ($projects as $project) {
$comments_collection[] = $project->comments;
}
}
$unreads = $comments_collection->where('unread', 1);
dd($unreads->count());
But i get this error:
Call to a member function where() on array
Anyone any idea how I can fix this?
The "standard" way of doing this is to track whether the comment owner has "read" the comment. You can do that fairly easily by adding a "unread" (or something equivalent) flag.
When you build your models, you should define all their relationships so that stuff like this becomes relatively easy.
If you do not have relationships, you need to define something like the following:
In User
public function projects()
{
return $this->hasMany('App\Models\Project');
}
In Project
public function comments()
{
return $this->hasMany('App\Models\Comment');
}
Once you hav ethose relationshipt, you can do the following. Add filtering as you see fit.
$count = $user->projects()
->comments()
->where('unread', true)
->count();
This is then the number you display to the user. When they perform an action you think means they've acknowledged the comment, you dispatch an asynchronous request to mark the comment as read. A REST-ish way to do this might look something like the following:
Javascript, using JQuery:
jQuery.ajax( '/users/{userId}/projects/{projectId}/comments/{commentId}', {
method: 'patch'
dataType: 'json',
data: {
'unread': false
}
})
PHP, in patch method:
$comment = Comment::find($commentId);
$comment->update($patchData);
Keep in mind you can use Laravel's RESTful Resource Controllers to provide this behavior.
try this
$unreads = $project->comments()->where('unread', 1);
dd($unreads->count());
EDIT
My be Has Many Through relation will fit your needs
User.php
public function comments()
{
return $this->hasManyTrough('App\Project', 'App\Comment');
}
Project.php
public function comments()
{
return $this->hasMany('App\Comment');
}
then you can access comments from user directly
$user->comments()->where('unread', 1)->count();
or I recommend you define hasUnreadComments method in User
public function hasUnreadComments()
{
$return (bool) $this->comments()->where('unread', 1)->count();
}
P.S.
$uid = Auth::user()->id;
$projects = User::find($uid)->projects;
this code is horrible, this way much better
$projects = Auth::user()->projects;
I have a list of properties for a real estate application and im trying to implement a like/unlike functionality based on each property detail. The idea is to add a like or remove it matching the current property and user. This is my code so far, but it only remove likes so it doesnt work as expected. If anyone can suggest for a better approach ill be appreciated.
//Controller
public function storeLike($id)
{
$like = Like::firstOrNew(array('property_id' => $id));
$user = Auth::id();
try{
$liked = Like::get_like_user($id);
}catch(Exception $ex){
$liked = null;
}
if($liked){
$liked->total_likes -= 1;
$liked->status = false;
$liked->save();
}else{
$like->user_id = $user;
$like->total_likes += 1;
$like->status = true;
$like->save();
}
return Redirect::to('/detalle/propiedad/' . $id);
}
// Model
public static function get_like_user($id)
{
return static::with('property', 'user')->where('property_id', $id)
->where('user_id', Auth::id())->first();
}
// Route
Route::get('store/like/{id}', array('as' => 'store.like', 'uses' => 'LikeController#storeLike'));
#Andrés Da Viá Looks like you are returning object from model. In case there is no data in database, it will still return an object - so far my guessing. Can you do something like below in the if($liked){ code?
Try this instead:
if(isset($liked -> user_id)){
Also try to print $liked variable after try and catch blocks. Use var_dump.
If this still does not work for you then let me know. I will try to create code based on your question.
Fix it by adding a where clause in my model to make the status equal to True ->where('status', 1)->first();