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.
Related
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).
I've been getting an error "Undefined property: Illuminate\Database\Eloquent\FactoryBuilder::$id " on my php Laravel code when I run the command php artisan db:seed. Although not all tables I've created are affected, 2 of them remain empty with no data to be shown in them. Here's the code that I've written for them.
namespace Database\Factories;
use App\Models\Product;
use App\Models\Category;
use Faker\Generator as Faker;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class ProductFactory extends Factory
{
protected $model = Product::class;
public function definition()
{
return [
"title"=>$this->faker->sentence,
"slug"=>Str::slug($this->faker->sentence),
"description"=>$this->faker->paragraph,
"price"=>$this->faker->numberBetween($min=100,$max=900),
"old_price"=>$this->faker->numberBetween($min=100,$max=900),
"inStock"=>$this->faker->numberBetween($min=1,$height=10),
"image"=>$this->faker->imageUrl($width=640,$height=480),
"category_id"=>factory(Category::class)->id,
];
}
}
The error highlights the last line of my code ""category_id"=>factory(Category::class)->id,"
Here's is the code that's supposed to populate the 2nd table called "Order Factory"
Order Factory
<?php
namespace Database\Factories;
use App\Models\User;
use App\Models\Order;
use Faker\Generator as Faker;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class OrderFactory extends Factory
{
protected $model = Order::class;
public function definition()
{
return [
"user_id"=>factory(User::class)->id,
"product_name"=>$this->faker->word,
"qty"=>$this->faker->numberBetween($min=1,$height=10),
"price"=>$this->faker->numberBetween($min=100,$max=900),
"total"=>$this->faker->numberBetween($min=1000,$max=9000),
];
}
}
Yesterday, an error was appearing at the line ""user_id"=>factory(User::class)->id" until when I added the "->id" line in my code, then the error wasn't showing anymore. I'm using the faker model to try and populate the fake users inside my db. If anyone has any knowledge why this error is showing up when I run the code and has any expertise in laravel8, help me fix this error so I can seed data into my db.
It looks like you're calling the factories wrong.
"user_id"=>factory(User::class)->id,
Should be
"user_id"=> User::factory()->create()->id,
Only if you create the entity you can access its ID.
Be aware: It's the same in your product factory.
More details described in the docs https://laravel.com/docs/8.x/database-testing#instantiating-models
Friends I am working on a Laravel Project. I have came across a problem where I am trying to use an OrderBy() method. The error message I get is
* BadMethodCallException*
Method orderBy does not exist.
Here my controller code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Episode;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Carbon;
class EpisodeController extends Controller
{
public function __construct()
{
$this->middleware('admincheck');
}
public function index()
{
$episodes = Episode::paginate(10)->orderBy('episode_no','desc');
return view('episode.index',compact('episodes'));
}
In the index() I have used paginate function and then orderBy function which I think is the source of error but I don't know why? If I use only paginate function I don't get error. And also If I use other functions like latest function after paginate I also get same kind of error. I don't Know what is wrong with my code so please guys help me. thank you.
Use it as
$episodes = Episode::orderBy('episode_no', 'DESC')->paginate(10);
You might need to put "orderby()" in front of the "paginate()" in terms of no function "orderby" for the paginate object.
im learning about laravel and im following some videos from laracasts, but im having a issue in displaying the data from the controller, i made all right, but still appears me empty array, the instance Card isnt working, here is my code:
Model:
Card.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Card extends Model
{
//
}
route:
Route::get('cards/{card}', 'CardsController#show');
CardsController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Card;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CardsController extends Controller
{
public function show(Card $card)
{
return $card;
//$card = Card::find($card);
//return view('cards.show', compact('card'));
}
}
What you are attempting is called "Route Model Binding" and it seems to me that you are using Laravel 5.1 or lower (where route model binding is not implicit).
If you are using Laravel 5.2 or higher that code should just work. https://laravel.com/docs/5.3/routing#route-model-binding
But, if you are in Laravel 5.1 you need to do an additional step: https://laravel.com/docs/5.1/routing#route-model-binding
In the provider class RouteServiceProvider, in the boot method, you need to bind which route name {card} should bind to which Model, in this case Card.
So, you do something like this:
public function boot(Router $router)
{
parent::boot($router);
$router->model('card', \App\Card::class);
}
If you add that, the router will know that when it finds {card} it should get that number and do the Card::findOrFail with the ID automatically and if the model is found it will be passed down to your controller.
First of all, you will need to add the fillable protected property to your Eloquent model! Now, on to the good part.
In your routes file you have
Route::get('cards/{card}', 'CardsController#show');
This code, in a nutshell, will pass the card ID to your show function in your CardsController class. Eg. for this route: https://example.com/cards/5, it will in essence call the function show like this: show(5). In your code, you have that the show parameter is typehinted to be a Card. This is wrong. This is going to be an integer.
Thus, what you really need to do is check whether this ID exists and then pass the relevant information to your view. Something like this:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Card;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class CardsController extends Controller
{
/**
* Show the relevant card information
*
* #param $card This is the card ID (its an integer)
*/
public function show($card)
{
$card = Card::findOrFail($card);
return view('cards.show')->with(compact('card'));
}
}
I am working on api part in Laravel 5.2 and trying to fetch the details from Strava. As mentioned in this link http://socialiteproviders.github.io/providers/strava I have done all the steps. In the controller I wrote a function to pass the access token of the user. This is the function which I am using public function
<?php
namespace App\Http\Controllers\Api\v1;
use Illuminate\Http\Request;
use Auth;
use Socialite;
use App\Models\UserTrackerSettings;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class StravaController extends Controller
{
/**
* Get the user by token
*
* #return \Illuminate\Http\Response
*/
public function getTrackerAccess()
{
$trackerDriver = Socialite::driver('strava');
$getToken = UserTrackerSettings::where('tracker_source_name', 'strava')
->where('user_id', Auth::user()->id)->first();
$access_token = $getToken->access_token;
return Socialite::getUserByToken($access_token);
}
}
But when I run the the link in postman I am getting this error
FatalErrorException in StravaController.php line 23:
Call to undefined method SocialiteProviders\Manager\ServiceProvider::driver()
It would be great if someone could help me. Thanks in advance!
Make sure that the actual driver is in there. Afterwards, since I don't see any class inclusions in there, you might need to call that class like this \App\Socialite::driver('strava') or just \Socialite::driver('strava'), I just don't know if that is the full code for your controller or not.