Laravel / Mongdb - DB::collection() is not working - php

I am following this Laravel/Mongodb package: https://github.com/jenssegers/. Here if you go to this section https://github.com/jenssegers/laravel-mongodb#basic-usage-2 you can see that they are using DB::collection() method and passed the collection name to that.
Now, in my controller, I am trying to do this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\Import;
use App\Models\Projects;
use Jenssegers\Mongodb\Collection;
use Jenssegers\Mongodb\Query\Builder;
class ImportController extends Controller
{
public function get_all_products() {
// Predefined key
$predefined_keys = [ 'image_link', 'title', 'price', 'brand', 'link' ];
// Get all the products
//$get_products = Import::paginate(10);
$get_products = DB::collection('products_1')->get();
return response()->json($get_products, 200);
}
}
but I don't get any result. Can you tell me what I am missing here?
My goal is to set the collectioin name directly in this controller not in Model.
Update:.
Here is my Import Mode:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Eloquent\Model;
class Import extends Model
{
protected $connection = 'mongodb';
protected $collection = 'products_46';
// protected $table = 'projects';
}

Something is wrong with how you have configured this project.
From the documentation that you linked:
When using MongoDB connections, Laravel will automatically provide you with the corresponding MongoDB objects.
Yet in the comments you report that DB::collection('products_1')->get(); results in:
message": "Method Illuminate\\Database\\MySqlConnection::collection does not exist."
This error message is referencing MySQL rather than MongoDB. It seems you are using MySQL for other portions of your application per this question.
In any case, I think the answer is to be sure to load the packages appropriately (and perhaps also to disambiguate between namespaces if DB is separately defined in Illuminate\Support\Facades and is in scope for this portion of the code).

Related

Laravel - Retrieving associated model using all function

I am writing a program that has a many-to-many relationship between clients and concerns. I have configured my models to use the belongsToMany() function as outlined in the Laravel documents. Please see the code for the two models below:
Client.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
use HasFactory;
protected $fillable = [
'first_name',
'last_name',
'email',
'preferred_day',
'preferred_time',
'presenting_concerns',
'is_active',
];
public function invoices() {
return $this->hasMany(Invoice::class);
}
public function concerns() {
return $this->belongsToMany(Concern::class);
}
}
Concern.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Concern extends Model
{
use HasFactory;
protected $guarded = [
'concern',
];
public function clients() {
return $this->belongsToMany(Client::class);
}
}
I was able to create some sample data using factories and php artisan tinker. I am now in the process of building out my views. However when I call
$clients = Client::all()->concerns()
in my controller, I get a concerns does not exist error message. I did a dd on just Clients::all(), and I don't see the concerns attached to the returned model. From my understanding, with just the call to all() function, I just return the client model. However, I was hoping by calling the concerns() function, I would be able to return the concerns as well. Is it possible to retrieve all clients and their concerns in one call?
Please note that I can use Client::find(2)->concerns() but that does not help me in my case because that only returns the concerns for client with ID 2.
Yes you can do this. You need to eager load your relation of interest.
If you do the following, you will load the relation and will be able to see it when doing dd().
$clients = Client::with('concerns')->get();

Why does only some laravel routes return model attributes?

i´m studying laravel but having some doubts..
Controller
namespace App\Http\Controllers;
use App\ItemNfe;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class ItensNfeController extends Controller
{
public function edit($id,ItemNfe $itemNfe)
{
//i don´t want to have to make this select below
//$itemNfe = DB::table('itens_nfe')->where('id_itemnfe',$id)->get();
// dd($itemNfe); this dd() returns model attributes on few of my controllers only
return view...
}...
Model: (note i´m not using laravel convention but it´s informed)
namespace App;
use Illuminate\Database\Eloquent\Model;
class ItemNfe extends Model
{
protected $table = 'itens_nfe';
protected $primaryKey = 'id_itemnfe';
protected $fillable = [
'id_itemnfe','fk_venda', 'fk_produto'...
];
public function nfe()
{
return $this->belongsTo('App\Nfe'); //this is one diference among others models, but apparently doesn´t affects when i tested without this code.
}
}
The route i´m using is the same for everyone.. "resource routes"
At the first 2, i have the attributes returning, but not at the last one...
Route::resource('/usuarios', 'UsuariosController');
Route::resource('/nfes', 'NfesController');
Route::resource('/itensnfe', 'ItensNfeController');
The Url used is:
https://localhost/erpoverweb/public/itensnfe/1/edit
If needing more code please tell me... thanks!
If you don't want to manually search the database for the entry, you can use Laravel Container do perform a Dependency Injection. https://laravel.com/docs/7.x/container#introduction
public function edit(ItemNfe $itemNfe)
{
// Returns the model, and you didn't need to manually searched.
// Laravel automaticly injects this for you.
dd($itemNfe);
}
Sounds like you are looking for Route Model Binding (implicit at that). This requires that the route parameter name and the name of the parameter of the method signature for that route match.
public function edit(ItemNfe $itensnfe)
The resource route with resource name 'itensnfe' should make the parameter 'itensnfe'.
If you don't make these match you will just end up with Dependency Injection which would inject a new model instance.
Laravel 7.x Docs - Routing - Route Model Binding - Implicit Binding

SQL queries from database with Laravel

I'm using Laravel and trying to do an SQL query from my Controller in a public function, but I'm really confused where I would put my table in the argument and if quotes go around the argument. Here is my code
public function selectMethod(){
$results = DB::select('select firstname from people where id = 1');
print_r($results);
return view('pages.selectMethod');
}
table is called people
My .env is configured to my database correctly and I get this error
FatalErrorException in AboutController.php line 90:
Class 'App\Http\Controllers\DB' not found
Thanks !
you should add use Illuminate\Support\Facades\DB;
at the top of your page
for example :
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*
* #return Response
*/
public function index()
{
$users = DB::table('users')->get();
return view('user.index', ['users' => $users]);
}
}
Your error clearly states: Class 'App\Http\Controllers\DB' not found
Hence just use DB in your class. Add:
use DB;
At the top of the file just below the namespace line.
Also, I would suggest you to use Eloquent for your queries. It will make your life a lot easier and your code a lot beautiful.

Using Laravel 5 Model

I have created a model using
php artisan make:model Sessions
which creates a model named Sessions in the App\ folder. My Model (Sessions) and the controller(School) calling the model are below
Model (Sessions):
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Sessions extends Model {
//
protected $table = "sch_sessions";
protected $primaryKey = "session_id";
}
Controller (School)
<?php
namespace App\Http\Controllers;
use App;
class SchoolController extends Controller {
public function sessionManagement(){
$Sessions = Sessions::all();
}
}
I get the following error
FatalErrorException in SchoolController.php line 7: Class
'App\Http\Controllers\Session' not found
I've tried putting the model in a folder and "use"ing it but nada. I'm stumped as to why the error is referring to a controller in the first place. Can anyone see something I don't (can't) please?
add on the top
use App\Sessions;
or use it with prefix
\App\Sessions::all();
If user Ali Mohammed's answer doesn't clear it up for you, it looks to me like your error is happening elsewhere. App\Http\Controllers\Session note Session is not plural.
Are you attempting to use the Session class elsewhere in your controller? If so, make sure to prefix it so it's using the Session declared in the global namespace. You can do this with \Session.

Save data into database in Laravel 5

First
I wrote a migration script.
Second
I run the php artisan migrate to migrate the table into my database.
Database
Now, I have a subscribes table in my database.
It has 2 fields : id, and email.
Route
Route::post('/subscribe', array('as' =>'subscribe','uses'=>'AccountController#postSubscribe'));
Model
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class Subscribe extends Model {
protected $table = 'subscribes';
//Validation Rules and Validator Function
public static function validator($input){
$rules = array(
'email' =>'required|email'
);
return Validator::make($input,$rules);
}
}
Controller
<?php namespace App\Http\Controllers;
use Input, Validator, Auth, Redirect;
class AccountController extends Controller {
public function postSubscribe() {
$subscribe = new Subscribe; <-------- Line#46 (BUG HERE)
$subscribe->email = Input::get('email');
$subscribe->save();
dd("Hi");
return Redirect::to('/')
->with('success','You have been successfully subscribe to us.');
}
}
?>
Error
Questions
Why can't I do $subscribe = new Subscribe;?
What is the best practice to insert data into database using Laravel 5 ?
Update
Thanks to #Mark Baker.
It seems that I have an issue with my namespace.
This namspacing is a bit confusing to me right now.
Can someone please clarify or explain that a bit ?
Anything is appreciated.
Thanks in advance.
Here is a high level overview of how namespaces work in PHP to try and help you understand this and give you a solution to your problem.
<?php
// This is the namespace of this file, as Laravel 5 uses PSR-4 and the
// App namespace is mapped to the folder 'app' the folder structure is
// app/Http/Controllers
namespace App\Http\Controllers;
// Use statements. You can include classes you wish to use without having
// to reference them by namespace when you use them further on in this
// namespaces scope.
use App\Subscribe;
class MyController extends BaseController
{
public function postSubscribe()
{
// You can now use the Subscribe model without its namespace
// as you referenced it by its namespace in a use statement.
$subscribe = new Subscribe();
// If you want to use a class that is not referenced in a use
// statement then you must reference it by its full namespace.
$otherModel = new \App\Models\Other\Namespace\OtherModel();
// Note the prefixed \ to App. This denotes that PHP should get this
// class from the root namespace. If you leave this off, you will
// reference a namespace relative to the current namespace.
}
}
You can try this, Simply use it :
$subscribe = new App\Subscribe;
Use App\Subscribe;.
Then you can use $subscribe = new Subscribe; in your code.

Categories