$store_obj = new account;
$x = \Auth::user()->id
$old = account::where('id',$x)->first();
echo $old->wallet;
$new = Input::get("update");
echo $new;
$upd = sum($old,$new);// strucked here
echo $upd;
I couldn't find sum function in Laravel helper docs. AFAIK, sum is one of aggregate method of query builder. I don't get on what you're trying to achieve, but I'll just assume you're going to update the model with adding those model value with given input value.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\account;
use Auth;
use App\Http\Requests;
class YourController extends Controller
{
public function update(Request $request)
{
$update = $request->input('update');
$id = Auth::user()->id;
$account = account::where('id', $x);
$account->increment('wallet', $update); //<---
$updated = $account->first();
return $updated;
}
}
I don't recommend the usage of native PHP echo, print_r or var_dump for debugging purpose. Use built-in Laravel dump or dd instead.
Of course, from code above, you need to validate user input before storing to DB.
Related
I am new to writing tests and I was wondering if what I am doing here is correct.
Basically I wanna write a test to check if the settings are correct but I use a record straight from my database.
Everything works great but I was wondering what if my database is empty? This test will never work
So what is best practice here?
my test:
/** #test */
public function settings_for_ftp_flysytem_is_correct_test()
{
$clientSettings = Client::where('category', 'ftp')->first()->settings()->get();
$this->assertArrayHasKey('host', $clientSettings);
$this->assertArrayHasKey('username', $clientSettings);
$this->assertArrayHasKey('password', $clientSettings);
$this->assertArrayHasKey('port', $clientSettings);
$this->assertArrayHasKey('root', $clientSettings);
}
I reckon the easiest solution is to use DatabaseTransactions trait and model factories. It is always a good idea to generate test data for every test case.
<?php
// ClientFactory.php
use Faker\Generator;
$factory::define(App\Setting::class, function (Generator $faker) {
return [...];
});
<?php
// SettingFactory.php
use Faker\Generator;
$factory::define(App\Setting::class, function (Generator $faker) {
return [...];
});
use Tests\TestCase;
use Illuminate\Foundation\Testing\DatabaseTransactions;
use App\Client;
use App\Setting;
class SettingsTest extends TestCase
{
use DatabaseTransactions;
public function test_client_has_settings()
{
// 1. Arrange.
$client = factory(Client::class)->create();
$settings = factory(Setting::class, 2)->create();
$client->settings()->saveMany($settings);
// 2. Act.
$response = $this->getJson("/clients/{$client->id}/settings");
// 3. Assert.
$response->assertJson([...]);
}
}
The above code is an example. For more info, pls check the following resources:Laravel Docs, Build a Forum with Laravel, Test-Driven Laravel.
I have store table related to product table, that have product.rating (int) 1 to 5
I want to find store that have average product rating 3 star or any based on my post data
My code
$store = new Store;
if ((int)$request->input('store-rating')>0) {
$store->whereHas('product',function($query) use($request) {
$rate = $request->input('product-rating');
$query->where(DB::raw('AVG(rating)'),$rate);
});
}
$store->with('product');
$thestore = $store->paginate(6);
return $thestore;
its always return all data like its ignore my POST store-rating value
Here is my Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as AuthUser;
use Illuminate\Support\Facades\Auth;
use App\ModelBuilder;
class Store extends AuthUser
{
use SoftDeletes;
protected $guarded = [];
protected $dates = ['deleted_at'];
public function product(){
return $this->hasMany('App\Product');
}
}
Solution
as answered below I should be using groupBy and havingRaw to make the query work, but it turn out that is not my only problem in the code
I changed the code to:
$store = Store::with('session');
if ((int)$request->input('store-rating')>0) {
$store->whereHas('product',function($query) use($request) {
$rate = $request->input('product-rating');
$query->groupBy('rating')->havingRaw('AVG(rating) = '.$rate);
});
}
$thestore = $store->paginate(6);
return $thestore;
its seem I cannot use $store = new Store; to start my model query
Hope this can help others.
Try using havingRaw
$query->grouBy('rating')->havingRaw('AVG(rating) = '.$rate);
don't forget the group by
I'm mainly working on two models right now, Form and Notification, and a many-to-many relationship is set up and working for most Eloquent commands, except for whereHas and has. Both just return an empty array, [].
It seems like the developer has had trouble with getting this to work in the past, but seems to have solved it here.
Here's a sample of what I have so far, and what I've tried:
Form.php
class Form extends Eloquent {
protected $connection = 'mongodb';
public function notifications(){
return $this->belongsToMany('App\Api\Forms\Notification', null, 'form_ids', 'notification_ids');
}
}
Notification.php
class Notification extends Eloquent {
protected $connection = 'mongodb';
public function forms()
{
return $this->belongsToMany('App\Api\Forms\Form', null, 'notification_ids', 'form_ids');
}
}
NotificationController.php
<?php
namespace App\Http\Controllers;
use App\Api\Forms\Notification;
use App\Api\Forms\Form;
class NotificationController extends Controller
{
public function getByFormTitle($form_title)
{
// This code retuns the relationship as expected.
// Any forms that are assigned to it are returned.
// $n = Notification::first();
// $n->forms()->get();
// This also returns the relationship correctly, same as before.
// $f = Form::first();
// $f->notifications()->get();
// Nearly identical to the Laravel docs. This returns an empty array, []
$notifications = Notification::whereHas('forms', function ($query) use ($form_title) {
$query->where('form_title', $form_title);
})->get();
return $notifications;
}
}
I get the same result if I use Notification::has('form')->get().
So my question is:
Is it possible to use whereHas and has in Jenssegers\Mongodb Eloquent? Do I have to use different syntax than the official Laravel documentation for it, or do I have to make a raw Mongo query for this?
I have class that allows to export data from database.
There is method that takes parameter $table:
use App\User;
public function query($table){
return User::get();
}
Problem is that I need to change $table in request. In this case I have default imported class use App\User; that allows me to use object-model User.
But if I want to use object dinamicly like as parameter?
So, I can do that:
if($table == "users"){
return User::get();
} else if ($table == "clients") {
return Client::get();
}
And import all model-classes in top class.
But this is not good way, I thing.
Not sure if this is what you are looking for, but you could try and create a map to map tables to objects.
$map = array('users' => User::class, 'clients' => Client::class);
$object = $map[$table];
return $object::get();
I'm using facebook JS to log in users to a laravel 5 application.
I'm able to add the information to the database correctly but I'm trying to log the user in manually and can't figure it out.
Here is my controller:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\lib\TopAdditions;
use App\Http\lib\GeneralFunctions;
use App\User;
class FacebookLoginController extends Controller{
public function FacebookRegistration(){
$facebook = new User();
$isThereAUser = User::where('name', $_GET['name'])->get();
if(!count($isThereAUser) > 0){
$facebook->name = $_GET['name'];
$facebook->email = $_GET['email'];
$facebook->password = sha1($_GET['password']);
$facebook->remember_token = $_GET['token'];
$facebook->save();
$id = User::where('name', $_GET['name'])->get();
$this->LoginUser($id);
}
}
public function LoginUser($id){
\Auth::login($id[0]['id'],true);
}
}
When I run that and there is no such user in the database, the user is created and I get this message when the manual login is attempted:
ErrorException in Guard.php line 425:
Argument 1 passed to Illuminate\Auth\Guard::login() must implement interface Illuminate\Contracts\Auth\Authenticatable, integer given
I've been searching the web for similar situations but couldn't find anything that will help...
Please help me!
You should pass the user object, not the id, to Auth::login. So just change your function to be like this:
public function LoginUser($user){
\Auth::login($user, true);
}
I had the same problem, this is the solution that worked for me in Laravel 5.4:
public function LoginUser($id){
$user = User::find($id);
auth()->login($user);
}