Laravel Query builder returning null - laravel

I am trying to run the query below but I keep getting null return.
$result = Order::with(['customers', 'team'])->where('customers_id','=', $custid)->select(sprintf('%s.*', (new Order)->table));
Then I changed it to
$result = Order::with(['customers', 'team'])->where(function($query) use ($cust) {$query->where('customers_id', $cust);})->select(sprintf('%s.*', (new Order)->table));
still returns null.
customers_id belongs to the orders table and references the customer's table. I am getting the $custid from the URL parameter.
If I replace $custid with an integer for example 3, it returns all orders for the customer with id 3. I have spent hours trying to resolve the issue. I have hosted on Heroku and localhost but nothing works.

Your problem is the way you're getting the url parameter. Put your url parameter in your method declaration.
Check the Laravel docs under Dependency Injection & Route Parameters here
public function index(Request $request, $custid) {

Related

Laravel Eloquent model events on created user

I'm trying to automatically create a profile for a user when a user is created.
I'm using the created event and overriding the boot() method. But I when call the create() method on user->profile->create(), it says create was called on null. I checked and profile is null in this.
Here's the code:
static::created(function ($user) {
// it returns profile as null, thus create() can't be used on null.
$user->profile->create(['title' => $user->username,]);
});
Can anyone help me understand this? It's working in my tutor's code, and he is using Laravel 5.8 but I have version 7.1.
$user->profile returns the related model if any exists. You have to do $user->profile() which returns a query builder to query the relation. Try to do it like so:
$user->profile()->create(['title' => $user->username,]);

Laravel Error while retrieving a Model with a custom connection

I have a Model Correo with a custom connection that changes dinamically.
The problem is that when I want to retrieve results from the database like this: Correo::on(session('conexion'))->get(), session('conexion') has the connection name, the following error appears:
Call to a member function newCollection() on null
I can get the results using this: DB::connection(session('conexion'))->table('correos')->get(), but I need the Model's methods and the previous one just returns a generic Collection.
Thanks!
You can use setConnection function
$correo = new Correo;
$correo->setConnection('yourConnectionName');
$data = $correo->find(1);
dd($data);
So based on the session ( if you don't have that many remote connections )
if (session('xyz')) {
$correo->setConnection('xyz');
} else {
$correo->setConnection('pqr');
}
`
Well, I solved it, when I created the model I wrote every property and then created every getter and setter, apparently it didn't like the new setConnection setter. I don't know why, but it stopped me from using it.

Page you are looking for not found laravel 5.5

I am getting the
Sorry, the page you are looking for could not be found.
On Laravel 5.5. I am sure I'm missing something very small. But not sure what it is because I'm a laravel learner. Please see below:
ROUTE
Auth::routes();
Route::get('/curriculum-sections','CurriculumsectionsController#index')->name('curriculum-sections');
Route::resource('/curriculum-sections','CurriculumsectionsController');
CONTROLLER
public function show(Curriculumsection $curriculumsection)
{
//
$curriculum = Curriculum::findOrFail($curriculumsection->id);
return view('curriculum-sections.show', ['curriculum'=>$curriculum]);
}
and I also made sure that the page exists in the views folder. While troubleshooting I also did php artisan route:list and this is what I got
Edit:
I am accessing the error from:
http://localhost:8000/curriculum-sections/1
The problem is that your route defines id for model Curriculumsection. You're using model binding, which will automatically query for Curriculumsection::findOrFail(route_id) (in your case route_id is 1). And then you're using the same id to query model Curriculum as well, with ->findOrFail(route_id).
So in order for this route to return anything other than 404, you have to have a record of Curriculumsection with id 1 and a record of Curriculum with id 1 in your database.
I'm not sure how your database is set up, or how these 2 models are related to each other, but definitely not by same id (otherwise, why not have all data in the same table).
Something like this would make more sense (binding the Curriculum model directly):
public function show(Curriculum $curriculum)
{
return view('curriculum-sections.show', ['curriculum'=>$curriculum]);
}
This would bind the Curriculum model to the route and automatically fetch the one with passed in id.
Or something like this for your use case, but it assumes that you have a working relationship called curriculum() on your Curriculumsection model:
public function show(Curriculumsection $curriculumsection)
{
$curriculum = $curriculumsection->curriculum;
return view('curriculum-sections.show', ['curriculum'=>$curriculum]);
}
I dont think that you need the first get route. You just define the Route::resource(...) and that's it. Laravel handles the different requests.
See here -> Resource Controllers

Laravel Auth User

In my controller i'm doing
$user = Auth:user()->get();
dd($user);
This is giving me the list of all users from my database.
why?
The other answers either explain how to solve your problem but not properly why this happens.
The laravel documentation states (source):
The get method returns an Illuminate\Support\Collection containing the results where each result is an instance of the PHP StdClass object.
With the full documentation found here, with API references here.
In essence, the get function here returns a collection and not the User object. The get method on an QueryBuilder executes a select statement.
With the following snippet we can see what queries get executed.
DB::enableQueryLog();
Auth::user()->get();
dump(DB::getQueryLog());
This will output:
DB::enableQueryLog();
Auth::user()->where('id', 1)->get();
dump(DB::getQueryLog());
This will output:
The first query will indeed output the expected user, the second query will grab the user class from the Auth::user() and select all rows from that table.
When we execute the 3rd and 4th query we can see that we once more first get the expected user, the 4th query however does also get a user (in this case the user with id 1). This is due too the where and not the Auth::user().
What we can conclude from these results is that the get takes into account all query builder functions but not the parameters of the supplied class.
If you use a get on an object it will only take into account the Class of that Object.
As too solve your problem the other questions where correct and you can use:
$user = Auth::user();
To fetch the user.
Because get return collection
Laravel Doc
Just remove get() to get single user data
$user = Auth:user();
dd($user);
in this case get() method return user collection object
You can auth user data by :
$user = Auth::user(); instead of using get();
Your user id is: {{ $user->id }}
Your first name is: {{ $user->first_name }}
Your last name is: {{ $user->last_name }}
return User::where('id', auth()->id())->with(['something'])->first()

Trying to get property of non-object error occurs in my controller

Was trying to call orders made by a particular user
from my database but get error from my controller reporting from controller..
Public function getYourOrders {
$order = Order::where('user_id','=',Auth::user()->id)->get();
return View::make('orders.show')->with('order',$order);
}
This is where the errorexception is reporting from
If you don't have a logged in user, Auth::user()->id would give you that error.
If you work with framework version 4.1.26+ don't use Auth::user()->id to retrieve user's id.
Instead use id method:
Auth::id();
it will take care of returning null if there's no logged in user and it will not execute unnecessary DB query (when using DB driver)

Resources