Passing Laravel Collection to Vue - json

I am trying to return customers from model Customer where id < 10. I do have some in the database.
$customers = Customer::where('id', '<', 10)->get();
return json_encode(['customers' => $customers]);
The above code will error out "Trailing data"
and when I try to dd($customers), I get a list of the collection Customer
I have no idea why I keep getting that and why the model is returning raw collection and not an object of the list of customers???
It seems like a null date "updated_at" field is causing the error. don't know why!
Solved By:
on the Customer model I had to do:
//ask Laravel to not manage default date columns
public $timestamps = false;
also I to mutate those columns:
public function setDateRemindedAttribute($value)
{
if (strlen($value)) {
$this->attributes['date_reminded'] = Carbon::createFromFormat('d/m/Y', $value);
} else {
$this->attributes['date_reminded'] = null;
}
}
public function setUpdatedAtAttribute($value)
{
if (strlen($value)) {
$this->attributes['updated_at'] = Carbon::createFromFormat('d/m/Y', $value);
} else {
$this->attributes['updated_at'] = $_SERVER['REQUEST_TIME'];
}
}

Use response()->json() like this
$customers = Customer::where('id', '<', 10)->get();
return response()->json(['customers' => $customers]);

Related

How to fetch data from single column stored in array using laravel?

I need to fetch the each and every column individually from the field array_payout can anyone solve it
$currentMonth_start_Date = Carbon::now()->startOfMonth()->subMonth(1);
$currentMonth_end_date = Carbon::now()->subMonth()->endOfMonth();
$clients_referral_tree = DB::table('mam_referral_payout')
->select('clients.id', 'mam_referral_payout.*')
//->addSelect(DB::raw('SUM(mam_referral_payout.Final_amount) as referral_amount'))
->leftjoin('clients', 'clients.id', '=', 'mam_referral_payout.to_id')
->where('clients.id', '=', (Auth::user()->id))
->whereBetween('mam_referral_payout.created_at', [$currentMonth_start_Date, $currentMonth_end_date])->get();
$clientTree = [];
foreach ($clients_referral_tree as $tree) {
$clientThree = $tree;
$clientTree[] = $clientThree;
}
dd($clientTree);
You can add the following to your Model:
protected $casts = [
"array_payout" => "object"
];
Add an accessor for each attribute in your json like this for example:
public function getTotalAmountAttribute(){
return optional($this->array_payout)->total_amount;
}
You can use them like this:
$clientTree1->total_amount;

I can't get the data in appends with json in Laravel

I have two models in laravel project Item and ItemImgs
Item.php
class Item extends Model
{
protected $appends = [
'photo',
];
public function imgs()
{
return $this->hasMany(ItemImage::class);
}
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img.src;
}
}
it's worked in views
dd(Item::all()); //worked
{{ $cane->photo}}; //worked
but when I try to get json
return response()->json([
'items' => Item::with('imgs')->get(),
]);
// not worked. Got timeout 500
You cannot use dot notation in PHP.
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img.src; // Dot notation is not allowed
}
but you've to use:
public function getPhotoAttribute()
{
$img = $this->imgs->first();
return $img->src;
}
if what you're trying to do is to get the items that have imgs() then what you should do is query by relationship existence, as mentioned in the docs
https://laravel.com/docs/5.8/eloquent-relationships#querying-relationship-existence
'items' => Item::has('imgs')->get()
It is not possible to refer to the linked model tables in attributes. It works in views but gives out a memory error when outputting an array through json.
public function getPhotoAttribute(){
$img = ItemImage::where('item', $this->id)-
>first();
}
It works that way, but it's not elegant.

Customize database result [Symfony 4]

I have like a search Form
I want for example search by Categorie, diplome, salaire,
Categorie, diplome works good
but my probleme is in salaire ( type float), when the form salaire null i want the Query return all Result of Categorie, diplome and ignore salaire
and when form salaire not null, i want the query return result of categorie+diplome+salaire list
this the controller
$data = $form->getData();
$repository = $this->getDoctrine()->getRepository(Candidat::class);
$candidats = $repository->findListByFilter($data->getCategorie(),$data->getDiplome(),$data->getSalaire());
This is the repository
public function findListByFilter($categorie,$diplome,$salaire):array
{
return $this->createQueryBuilder('c')
->andWhere('c.categorie = :categorie')
->andWhere('c.diplome = :diplome')
->andWhere('c.salaire <= :salaire')
->setParameter('categorie', $categorie)
->setParameter('diplome', $diplome)
->setParameter('salaire', $salaire)
->getQuery()
->getResult()
;
}
I recommend you to use IFs to accomplish this kind of request:
public function findListByFilter(string $categorie, string $diplome, ?float $salaire = null): array
{
$qb = $this->createQueryBuilder('c')
->where('c.categorie = :categorie')
->andWhere('c.diplome = :diplome')
->setParameters([
'categorie' => $categorie,
'diplome' => $diplome
]);
if($salaire) {
$qb->andWhere('c.salaire <= :salaire')->setParameter('salaire', $salaire);
}
return $qb->getQuery->getResult();
}
You are using Symfony 4 so I recommend you to start using type-hint for your variables.

Base Table not found on unique value validation in MongoDB with laravel

I'm using laravel 5.3 with jenssegers/laravel-mongodb package for managing mongodb connections.
I want to check every time a user send a request to register a website in my controller if it's unique then let the user to register his/her website domain.
I wrote below code for validation but What I get in result is :
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'iranad.seat' doesn't exist (SQL: select count(*) as aggregate from `seat` where `domain` = order.org)
my controller code :
public function store(Request $request) {
$seat = new Seat();
$validator = Validator::make($request->all(), [
'domain' => 'required|regex:/^([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/|unique:seat', //validating user is entering correct url like : iranad.ir
'category' => 'required',
]);
if ($validator->fails()) {
return response()->json($validator->messages(), 400);
} else {
try {
$statusCode = 200;
$seat->user_id = Auth::user()->id;
$seat->url = $request->input('domain');
$seat->cats = $request->input('category');
$seat->filter = [];
if($request->input('category') == 'all') {
$obj['cats'] = 'false';
$seat->target = $obj;
} else {
$obj['cats'] = 'true';
$seat->target = $obj;
}
$seat->status = 'Waiting';
$seat->save();
} catch (\Exception $e) {
$statusCode = 400;
} finally {
$response = \Response::json($seat, $statusCode);
return $response;
}
}
}
My Seat Model :
namespace App;
use Moloquent;
use Carbon\Carbon;
class Seat extends Moloquent {
public function getCreatedAtAttribute($value) {
return Carbon::createFromTimestamp(strtotime($value))
->timezone('Asia/Tehran')
->toDateTimeString();
}
}
Obviously The validator is checking if domain is unique in mysql tables which causes this error, How can I change my validation process to check mongodb instead of mysql ?
I solved the problem, The solution is that you should add Moloquent to your model and define database connection :
namespace App\Models;
use Moloquent;
use Carbon\Carbon;
class Seat extends Moloquent
{
protected $collection = 'seat';
protected $connection = 'mongodb';
}

build a query with conditional where clause in eloquent model

I need to build a query with eloquent model including conditional where clause. I created something by searching google. But it doesn't seems to be working.
if ($status) {
$this->where('status', $status);
}
if ($assignedto) {
$this->where('assigned_to', $assignedto);
}
if ($fromDate != null && $toDate != null) {
$this->whereBetween('date', array($fromDate, $toDate));
}
$quotes = $this->orderBy('date', 'desc')->paginate(40);
This one returns all results without the filtering of status, assigned to and dates.
I just updated it by assigning $this to a new variable because when I assigned the query to $this, it shown an error, $this cannot be over written.
$quoteModel = $this;
if ($status) {
$quoteModel = $quoteModel->where('status', $status);
}
if ($assignedto) {
$quoteModel = $quoteModel->where('assigned_to', $assignedto);
}
if ($fromDate != null && $toDate != null) {
$quoteModel = $quoteModel->whereBetween('date', array($fromDate, $toDate));
}
$quotes = $quoteModel->orderBy('date', 'desc')->paginate(40);
which works perfectly now. But if somebody have some better option, please suggest. Thanks.
I added a scope to my model and call it from the controller. This way the actual filtering work is done in the model, the controller is just running the query through the filter scope.
Model:
I am getting URL parameters with Input::get, but you would also pass them as input parameters to the function.
public function scopeFilter($query)
{
$published = Input::get('published');
if (isset($published)) $query->where('published', '=', $published);
return $query;
}
Controller:
Here the query is run through the filter() before returning it to the view.
public function index()
{
return View::make('articles.index', [
'articles' => Article::with('writer')->filter()->get()
]);
}