CI4: I have created database object in Controller, i want to execute helper function which has some queries,
Question: How to access the database in Helper Functions in CI4?
you can use by adding these lines in your helper function
$db = db_connect();
$result = $db->query("SELECT * FROM table")->getResult();
You can access the builder from the model.
$model = new SomeModel();
$builder = $model->builder();
$builder->db //returns the db conn used in model
Related
Method Illuminate\Database\Eloquent\Collection::toSql does not exist.
occured when I tried this
My laravel version 6.20
$query = Car::where($criteria)
->get(['id'])->shuffle();
$sql = $query->toSql();
Log::info($sql);
When you execute the query using get() it will return an instance of Illuminate\Database\Eloquent\Collection class. And there's no method named toSql() on the Collection class.
If you want to inspect the sql you should
$query = Car::where($criteria)->select('id');
//Here $query is an instance of Illuminate\Database\Eloquent\Builder
//And it has a method named toSql
$sql = $query->toSql();
Log::info($sql);
$query->get()->shuffle();
You could use dd or dump methods for debugging purposes.
Source: https://laravel.com/docs/6.x/queries#debugging
I'm save my cart products as unserialized data from my cart session.
$order = new Order();
$order->cart = serialize($cart);
$order->code = strtoupper(str_random(15));
$order->user_id = Auth::user()->id;
$order->save();
now i need to unserialize the data to use it in my blade file, this is the function i'm using
$orders = Order::with('user')->findOrFail($order->id);
$orders->transform(function($order, $key){
$order->cart = unserialize($order->cart);
return $order;
});
dd($orders);
I'm getting this error
BadMethodCallException Call to undefined method App\Order::transform()
what seems to be the problem? and how can i unserialize my data;
any ideas ???
With findOrFail you retrieve just one instance of model, not a collection.
$orders = Order::with('user')->findOrFail($order->id);
Also what is $order->id you have your order model?
So
$order->load('user');
$order->cart = unserialize($order->cart);
Or do you want a collection then your code will work like this
$orders = Order::with('user')->get();
$orders->transform(function($order, $key) {
$order->cart = unserialize($order->cart);
return $order;
});
The problem is not about unserialize, it doesn't even get there. The problem seems to be related to an undefined method you are trying to use ($orders->transform).
Can you please provide the code in your Order class? Did you define the transform method there?
EDIT:
by using serialize you are kinda' missing the point of a relational database and the datatypes inherent in your database engine. Doing this makes data in your database non-portable, difficult to read, and can complicate queries.
Also, many tests prove that json_encode is faster than serialize.
I'm sure there must be a very simple way to do this - I would like to fill the user_id field on my resource with the authenticated user's id whenever a new instance of the resource is created.
In the store() method of my Resource model I have:
public function store(Request $request)
{
$input = $request->all();
$resource = Resource::create($input);
$resource->user_id = Auth::user()->id;
return $resource;
return 'Resource added.';
}
This works through a post API route, however whenever I add a new resource instance through Nova dashboard, it does not add the Auth user id. I'm guessing this because Nova doesn't use that Resource controller that I have set out?
I would appreciate suggestions!
Working on the assumption that you have relationship method User::resources() the following should work:
return $request->user()->resources()->create($request->all());
The way you have it doesn't work because you didn't save the resource after associating user with it.
I haven't used Nova yet, but since its also laravel and most likely Eloquent ORM I can tell the following.
In these two lines you've set the user_id but you haven't persisted the change:
$resource->user_id = Auth::user()->id;
return $resource;
You should add this line to save the changes you've done:
$resource->save();
As an alternative you could add the value already into your $input array:
$input = $request->all();
$input["user_id"] = Auth::user()->id;
$resource = Resource::create($input);
I just created an ResourceObserver. Saved the Auth()->user->id with the created method.
Registered the ResourceObserver to AppServiceProvider and NovaServiceProvider.
https://laravel.com/docs/5.7/eloquent#observers
https://nova.laravel.com/docs/1.0/resources/#resource-events
In the model class, add function like this:
public function save(array $options = array())
{
$this->user_id = auth()->id();
parent::save($options);
}
Just be carefull if you tend to use save in any other scenario so you don't overwrite existing user_id.
so basically i have an index page where i have to go to controller to fetch data from database
route:-
route::get('/index/{$x}', 'indexController#index');
index controller:-
$data = Data::where('name', $x)->get();
return View::make('index', compact('data');
then inside index page i have link that goes to second page
with same data, i d not want to query the same data as it may affect performance
route:-
route::get('/second', indexController#second);});
Second Controller:-
$data = $data->sortBy('id');
return View::make('second', compact('data');
i thought of saving data in global variable in controller
so i added private variable inside controller and try to access it through $this->data
but it did not work cause based on my search the controller will be closed after it returns view
so if i try access $this->data inside second function it will be empty
is it possible to save queried data (collection) in global variable
as i do not want to query same data for every page
your help will be appreciated
If you having same data on different pages that will not be solved using any kind of global variables. You need to cache query results. Please check cache in laravel docs https://laravel.com/docs/5.6/cache
Here is how that is usually done:
$data = Cache::get('some_cache_key');
if (empty($data)) {
$data = Data::where('name', $x)->get();
Cache::put('some_cache_key', $data, 60); //60 minutes
}
return View::make('index', compact('data');
There are multiple ways to achieve this. Either you can store the data in the Session and access all across the application
$data = Data::where('name', $x)->get();
session()->put('data', $data);
You can also use View::share('key', $data)
In your AppServiceProvider inside boot() method
public function boot()
{
View::share('data', Cache::get('data'));
}
In your controller.
$data = Data::where('name', $x)->get();
Cache::put('data', $data);
By this way you can access the data all across the application using {{ $data }} in your views.
hope this helps.
I know that we can insert array in Session as Session::push('person.name','torres') but how to keep laravel collection object such as $product = Product::all();,as like Session::put('product',$product);.Ho wto achieve this?
You can put any data inside the session, including objects. Seeing as a Collection is just an object, you can do the same.
For example:
$products = Product::all();
Session::put('products', $products);
dd(Session::get('products'));
Should echo out the collection.
You should convert it to a plain array, then convert them back to models:
Storing in the session
$products = Product::all()->map(function ($product) {
return $product->getAttributes();
})->all();
Session::put('products', $products);
Retrieving from the session
$products = Product::hydrate(Session::get('products'));
You can see an example of this method here.