Adding key-value to Laravel result object/collection - laravel

New to Laravel. Have what seems like should be a non-issue, but is causing a headache.
I'm trying to insert a key-value pair (bookingRef) within the result object/collection returned, such that the result would be:
[{"class_id":7,"class_name":"beginner","class_slots_avail":100,"class_slots_booked":53,"class_date":"2020-12-07 21:47:23","class_time":"09:25:00","class_reg_price":350, bookingRef: 127}]
I've tried methods such as push, put and merge that will insert the key-value after the object returned, but this is not what I require.
Here is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Booking;
use App\Http\Controllers\Auth;
use Illuminate\Support\Facades\Mail;
use DB;
class BookingsController extends Controller
{
//
function store(Request $request) {
$id = $request->input('class');
if(DB::table('classes')->where('class_id', '=', $id)->exists()) {
if(DB::table('classes')->where('class_id', '=', $id)->value('class_slots_booked')
< DB::table('classes')->where('class_id', '=', $id)->value('class_slots_avail')) {
$booking = new Booking();
$booking->class_id = $id;
$booking->user_id = \Auth::id();
$booking->save();
DB::table('classes')->where('class_id', '=', $id)->increment('class_slots_booked', 1);
if($booking) {
$confBook = DB::table('classes')->where('class_id', '=', $id)->get();
$confBook->bookingRef = $booking->id;
\error_log($confBook);
}
}
else return('CLASS FULLY BOOOOKED');
}
else return('CLASS NOT Available');
}
}

You can cut down on your queries and put this extra data in place with some adjustments:
function store(Request $request)
{
$id = $rquest->input('class');
$class = DB::table('classes')->where('class_id', $id)->first();
if ($class) {
if ($class->class_slots_booked < $class->class_slots_avail) {
$booking = new Booking();
$booking->class_id = $id;
$booking->user_id = $request->auth()->id;
if ($booking->save()) {
// adding the extra data
$class->bookingRef = $booking->id;
DB::table('classes')->where('class_id', $id)
->increment('class_slots_booked', 1);
$class->class_slots_booked++;
return view('view-booking', [
'bookings' => collect($class),
]);
}
// booking did not save
}
// unavailable
}
// class not found
}
This would be a little more convenient with a Model for the classes table and a relationship setup to Booking would be a plus as well.

I managed to resolve it, thanks to Lagbox's suggestion of using a model:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Booking;
use App\Models\Classes;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;
class BookingsController extends Controller
{
//
function store(Request $request) {
$id = $request->input('class');
$class = Classes::where('class_id', $id)->first();
if($class) {
if($class->class_slots_booked < $class->class_slots_avail) {
$booking = new Booking();
$booking->class_id = $id;
$booking->user_id = Auth::id();
if($booking->save()){
$class->where('class_id', $id)->increment('class_slots_booked');
$class->bookingRef = $booking->id;
return view('view-booking', ['bookings' => $class]);
}
}
else return('Class Fully Booked');
}
else return('Class Not Available');
}
};
From what I can see, the get() method returns an array with object(s), which is why object->new_property = value would not work. The first() method, however, seems to return a single object, which is why it would.
Seems I've got some reading up on models and collections to do.

Related

Laravel Spatie Searchable

I am trying to implement spatie searchable in my project and it is working fine when I am doing plain searches. But if I try to do some filtering it is not working and I have no idea though. I have added my code below:
My controller:
<?php
namespace App\Http\Livewire\SuperAdmin;
use Livewire\Component;
use Spatie\Searchable\Search;
use App\Models\Category;
class SuperAdminSearch extends Component
{
public $query;
public $searchResults = [];
public $name = [];
public function updated($property) {
$this->name = $this->categoryName();
if($property == 'query') {
$searchterm = $this->query;
$this->searchResults = (new Search())
->registerModel(Category::class, 'name')
->perform($searchterm);
}
if(empty($this->query)) {
$this->searchResults = [];
}
}
public function render()
{
return view('livewire.super-admin.super-admin-search');
}
}
my model:
protected $fillable = ['name', 'category_type'];
public function getSearchResult(): SearchResult
{
$url = route('super_admin_category_details', $this->id);
return new SearchResult(
$this,
$this->name,
$url
);
}
Now what I want to do is I want to display all the category names where category_type will be ADVERTISEMENT. that's all. But I stuck for this last few days.
Thank you
You have to use SearchAspect. This way you can also search for exact matches and even filter your query like you would using the query builder.
$searchResults = (new Search())
->registerModel(Category::class, function (ModelSearchAspect $modelSearchAspect) {
$modelSearchAspect
->addSearchableAttribute('category_name')
->where('category_type', 'your_category_type_id');
})->perform($searchterm);

Larave 6 l “Creating default object from empty value”

Here, I have setuo CRUD table with laravel, vuetify and vue . I could successfull create and read data from the database. But, for some reason my update and delete are not working. I am getting error like:
{message: "Creating default object from empty value", exception: "ErrorException",…}
exception: "ErrorException"
file: "C:\WinNMP\WWW\chillibiz\app\Sys\Http\Controllers\StageController.php"
line: 53
message: "Creating default object from empty value"
trace: [{file: "C:\WinNMP\WWW\chillibiz\app\Sys\Http\Controllers\StageController.php", line: 53,…},…]
My code are here:
StageController.php
<?php
namespace App\Sys\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Sys\Model\Stage;
class StageController extends Controller
{
public function index(Request $request)
{
$per_page = $request->per_page ? $request->per_page : 5;
$sort_by = $request->sort_by;
$order_by = $request->order_by;
return response()->json(['stages' => Stage::orderBy($sort_by, $order_by)->paginate($per_page)],200);
}
public function store(Request $request)
{
$uuid = Str::uuid()->toString();
$stage= Stage::create([
'id' => $uuid,
'code' =>$request->code,
'name' =>$request->name,
'description' =>$request->description,
]);
return response()->json(['stage'=>$stage],200);
}
public function show($id)
{
$stages = Stage::where('code','LIKE', "%$id%")->orWhere('name','LIKE', "%$id%")->orWhere('description', 'LIKE', "%$id%")->paginate();
return response()->json(['stages' => $stages],200);
}
public function update(Request $request, $id)
{
$stage = Stage::find($id);
$stage->code = $request->code; //line 53
$stage->name = $request->name;
$stage->description = $request->description;
$stage->save();
return response()->json(['stage'=>$stage], 200);
}
public function destroy($id)
{
$stage = Stage::where('id', $id)->delete();
return response()->json(['stage'=> $stage],200);
}
public function deleteAll(Request $request){
Stage::whereIn('id', $request->stages)->delete();
return response()->json(['message', 'Records Deleted Successfully'], 200);
}
}
Stage.php
<?php
namespace App\Sys\Model;
use Illuminate\Database\Eloquent\Model;
class Stage extends Model
{
protected $guarded = [];
}
I just found they you are using uuid as id not increment. that why you get error like that:
to solve your problem you need to add the field to your model;
<?php
namespace App\Sys\Model;
use Illuminate\Database\Eloquent\Model;
class Stage extends Model
{
public $incrementing = false;
protected $keyType = 'string';
protected $guarded = [];
}
I hope this time you can solve your problem. happy coding.
Edit you can read docs for more info

Create filter in laravel API controller

Hi i want to create a filter to show mosque with event or activities only. Any idea to display the mosque with activities or events only ?. This one from back-end that later will be fetch using react
namespace App\Http\Controllers;
use App\Event;
use App\Mosque;
use App\Activity;
use Illuminate\Http\Request;
class NotificationController extends Controller
{
public function list()
{
$mosques = Mosque::get();
$array = array();
foreach ($mosques as $mosque) {
array_push($array, [
'mosque_name' => $mosque->name,
'mosque_image'=> $mosque->image
]);
}
return $array;
return response()->json(['result' => $mosques]);
}
public function show(Request $request)
{
$mosque = Mosque::find($request->mosque_id);
$mosque->activities;
$mosque->events;
return response()->json(['result' => $mosque]);
}
}
To filter rows from database, which has particular relationship, you can use whereHas() function on QueryBuilder Instance.
$mosques = Mosque::whereHas('events')
->orWhereHas('activities')
->get();
This function will only returns mosques which has activities or events, other mosques will not fetch.
Also if you only need the name and the image you can filter them too
$mosques = Mosque::whereHas('events')
->orWhereHas('activities')
->get(['name','image']);
You can try this
public function show(Request $request)
{
$mosque = Mosque::find($request->mosque_id);
$mosque->activities;
$mosque->events;
return response()->json(['result' => $mosque->events ]);
}

Laravel trait function not found

I have look all over stackoverflow and google and I cannot seem to solve my trait function not found. I have tried composer dump-autoload, my composer.json have the app directory connected and even checked my namespace and trait names. Here is my user controller.
<?php
namespace App\Http\Controllers;
use App\User;
use App\Traits\ControllerTrait;
use App\Http\Requests\UpdateUser;
use Illuminate\Http\Request;
use App\Http\Requests\IndexUser;
class UserController extends Controller
{
use ControllerTrait;
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show multiple users.
*
* #return \Illuminate\Http\Response
*/
public function index(IndexUser $request)
{
$per_page = 50;
$order_by = 'id';
$sort_by = 'ASC';
if($request->has('per_page')) {
$per_page = $request->input('per_page');
}
if($request->has('order_by')) {
$order_by = $request->input('order_by');
}
if($request->has('sort_by')) {
$sort_by = $request->input('sort_by');
}
$users = User::when($request->has('select'), function ($query) use ($request) {
selectPrepare($query, $request->input('select'));
})->when($request->has('include'), function ($query) use ($request) {
if(!empty($request->input('include'))) {
$includedTables = explode(',', $request->input('include'));
$tables = array_map('trim', $includedTables);
return $query->with($tables);
}
return $query;
})->orderBy("{$order_by}", "{$sort_by}")
->paginate($per_page);
return response()->json($users);
}
}
}
Here is my Trait
<?php
namespace App\Traits;
trait ControllerTrait
{
/**
* Function: scopeSelectPrepare
public function selectPrepare($query, $select) {
if(!empty($select)) {
$selectedColumns = explode(',', $select);
$columns = array_map('trim', $selectedColumns);
return $query->select($columns);
}
return $query;
}
}
As you can see my name space for the Trait is App\Traits and call the use App\Traits\ControllerTrait in my controller then can the use ControllerTrait to get the functions from the trait. When I try to get the function to use in my query it says: Call to undefined function App\Http\Controllers\selectPrepare()
Is there something I am missing? I am new to the traits functionality of laravel but I thought I was following all of the examples and naming conventions. Can anyone see what I am doing wrong.
You need to use $this when accessing trait methods, just like you would for any other method:
$users = User::when($request->has('select'), function ($query) use ($request) {
$this->selectPrepare($query, $request->input('select'));

Call to undefined method Illuminate\Database\Query\Builder::products()

i am trying to Implement smart Search engine in my Laravel 5 With help of This Tutorial
https://maxoffsky.com/code-blog/laravel-shop-tutorial-3-implementing-smart-search/
i changes some code because this tutorial for laravel 4
now i am stuck here When i type any keywords like cup i got error on Network tab in my deleveloper tool
Call to undefined method Illuminate\Database\Query\Builder::products()
Here is my Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Http\Requests;
use App\Product;
use App\Category;
use Response;
class ApiSearchController extends Controller
{
public function appendValue($data, $type, $element)
{
// operate on the item passed by reference, adding the element and type
foreach ($data as $key => & $item) {
$item[$element] = $type;
}
return $data;
}
public function appendURL($data, $prefix)
{
// operate on the item passed by reference, adding the url based on slug
foreach ($data as $key => & $item) {
$item['url'] = url($prefix.'/'.$item['slug']);
}
return $data;
}
public function index()
{
$query = e(Input::get('q',''));
if(!$query && $query == '') return Response::json(array(), 400);
$products = Product::where('published', true)
->where('name','like','%'.$query.'%')
->orderBy('name','asc')
->take(5)
->get(array('slug','name','icon'))->toArray();
$categories = Category::where('name','like','%'.$query.'%')
->has('products')
->take(5)
->get(array('slug', 'name'))
->toArray();
// Data normalization
$categories = $this->appendValue($categories, url('img/icons/category-icon.png'),'icon');
$products = $this->appendURL($products, 'products');
$categories = $this->appendURL($categories, 'categories');
// Add type of data to each item of each set of results
$products = $this->appendValue($products, 'product', 'class');
$categories = $this->appendValue($categories, 'category', 'class');
// Merge all data into one array
$data = array_merge($products, $categories);
return Response::json(array(
'data'=>$data
));
}
}
my Product and Category model is blank because nothing on tutorial
Well based on your relationship between Product and Category Models you have to define product() function inside Category Model which represents your relationship. check This Link
For example - Assuming One-to-Many relationship (one category - Many Products) it will be like this -
Category Model -
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function product()
{
return $this->hasMany('App\Product');
// ^ this will change based on relationship
}
}
Product Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
public function category()
{
return $this->belongsTo('App\Category');
// ^ this will change based on relationship
}
}

Resources