stuck at laravel, trying to store an id in a variable - php

I want to store the user_id in the profile table into a variable. In my index function I have:
$userid = Profile::where('user_id', auth()->user()->id)
->first();
return view ('profile.index',[
'user' => $user,
'userid' => $userid,
'about' => $about,
and in my index view:
#if(Auth::user()->id == $userid)
<h3>hello</h3>
#endif
Yet, I get this error:
Object of class App\Models\Profile could not be converted to int (View: C:\xampp\laravelprojects\testfrihand\resources\views\profile\index.blade.php)

Change it to get user_id from the model instance
$userid = Profile::where('user_id', auth()->id)
->first()->user_id;
Notice1: When you call first() method, you'll get an instance of eloquent model. You should tell it what attribute do you want. Here, you want user_id. Either ->first()->user_id and ->first()->get('user_id') will give your desired answer.
Notice2: You can get id of current authenticated user by calling auth()->id

Not actually understand what do you need exactly.
But anywhere
$userid = Profile::where('user_id', auth()->user()->id)
->first();
Here you get a Profile Object, not an id.
Please specify your question: do you want to store user_id in this code, or to get user_id and use it in condition?

$user = auth()->user();
$whatEverYouWant= Profile::where('user_id', $user->id)->first();
return view ('profile.index',[
'user' => $user,
'userid' => $user->id,
'about' => $about
]

Related

Laravel : How to get all the rows from a table except the first one?

I want to select all the users in my table "User" except the first One cause its the admin,
im using this function index in my controller but it doesn't work .
public function index()
{
// this '!=' for handling the 1 row
$user = User::where('id', '!=', auth()->id())->get();
return view('admin.payroll',compact('user'))->with(['employees' => User::all()]);
}
Better to used here whereNotIn Method
Note: first you find the admin role users and create a static array
$exceptThisUserIds = [1];
$user = User::whereNotIn('id', $exceptThisUserIds)->get();
It's not a good idea to specify the admin user with just id. A better design would be using some sort of a flag like is_admin as a property of your User model.
Still you can use the following code to get the users who have an id greater than 1:
User::where('id', '>', 1)->get()
For getting data skipping the first one you should use skip() method and follow the code like below
public function index()
{
$user = User::orderBy('id','asc')->skip(1)->get();
return view('admin.payroll',compact('user'))->with(['employees' => User::all()]);
}

Retrieve multiple record from database in Laravel 5.2

I want to check if user login only if email exist and activated==1
set in database but activated always show null value.
Image 1:
Image 2:
Try this one
$user = DB::table('users')->where([
['email', '=', $email],
['activated', '=', '1'],
])->get();
or
make your where clause with array to check multiple conditions.
You can use Model class to get data using where clause.
See Queries: Laravel
Another Example (eloquent):
$matchThese = ['email' => $email, 'activated' => '1'];
//........
//........
$results = User::where($matchThese)->get();

Showing orders of user in laravel

I'm trying to give ability on user to see his orders. How can I query the database.. I'm trying something like this but I got empty page.. I mean nothing from database. May be my query ins't correct.
This is my controller
public function viewOrders() {
$user_order = self::$user->user_id;
$orders = Order::where('user_id', '=', $user_order);
return View::make('site.users.orders', [
'orders' => $orders
]);
}
Am I getting correctly user_id here? I'm not sure...
Update: I have this in my User model
public function orders() {
return $this->hasMany('Order', 'user_id', 'user_id');
}
Ok, so based on your route+button+model do it like this
$orders = self::$user->orders()->orderBy('order_id', 'asc')->get();
return View::make('site.users.orders', [
'orders' => $orders
]);
this should work.. You can remove orderBy clause if you don't need it.
If you have Authentication set properly you can do the following.
public function viewOrders(){
$user = Auth::user();
return view('site.users.orders',[
'orders' => $user->orders
]);
}
When you use the relationship without using the calling parentheses you get a collection of models which are queried if they're not already loaded. This is called lazy loading, if you want to load a relationship before accessing it you can use eager loading. In this case, it is not necessary though.

Laravel Create OR update related model

I have the following function to create a new related model;
//Create the results entry
$result = new Result([
'result' => $total,
'user_id' => $user->id,
]);
//attach it to the fixture - parse through looking for the user_id or opponent_id
//to match the current user in the loop.
$fixture = LeagueFixture::where('league_id', $league_id)
->where('gameweek', $gameweek)
->where(function($q) use ($user){
$q->where('user_id', $user->id)
->orWhere('opponent_id', $user->id);
})
->first();
$fixture->results()->save($result);
The ->save() at the end does most of the magic, attaching the correct fixture_id to the result table. The problem is that if the function is run again, it creates new entries for the same results.
There is a firstOrCreate() method, but i don't know how to use this when saving a related model.
Thanks
It's exactly like this: http://laravel.com/docs/5.0/eloquent#insert-update-delete.
//Create or find a existing one...
$result = Result::firstOrCreate([
'result' => $total,
'user_id' => $user->id,
]);
//grab fixture...
$fixture = LeagueFixture::where('league_id', $league_id)
->where('gameweek', $gameweek)
->where(function($q) use ($user){
$q->where('user_id', $user->id)
->orWhere('opponent_id', $user->id);
})
->first();
//associate (set fixture_id in $result equals to $fixture's key)
//any previous association will disappear.
$fixture->results()->associate($result);
//save to write changes in the database.
$result->save()
you can check here (https://github.com/laravel/framework/blob/5.0/src/Illuminate/Database/Eloquent/Model.php#L559). Laravel will search in your database and return if it found it or create a new.

How to get the id of the current model in Laravel when saving

I am working in a Laravel 5 application. I try to save a comment for a projet and I don't know how to get the $comment->project_id value.
Here is my simplified controller
public function store( CommentsFormRequest $request )
{
$comment = new Note;
$comment->message = Input::get('message');
$comment->project_id = $note->project->id;
$comment->user_id = Auth::id();
$comment->save();
return Redirect::back();
}
and here is my simplified form
{!! Form::open(array('route' => 'notes.store')) !!}
{!! Form::textarea('message', '', array('placeholder'=>'Message')) !!}
{!! Form::submit('Ajouter la note') !!}
{!! Form::close() !!}
When I try to save, I get this error:
Trying to get property of non-object
I guess it's because it tries to get the sollicitation_id of the new object wich is null. How should I get the current project_id value?
Update
Conclusion: I used an hidden field and followed #tommy 's recommendation.
My controller now uses
$note->project_id = $request->input('project_id');
and my hidden field is
{!! Form::hidden('project_id', $project->id ) !!}
Only IF the table primary column name is 'id':
$model->id;
Regardless of primary column name:
$model->getKey();
In the store method, you try to get the property project of the variable $note, which does not exist. You should pass the project ID to the store method by either adding it to the route or adding a hidden field project_id to your form.
Then, your store method should look something like this:
public function store($project_id, CommentsFormRequest $request )
{
$project = Project::find($project_id); // $project_id is transmitted over the URL
$comment = new Note; // I'd alias Note as 'Comment', or rename '$comment' to '$note' because this can be confusing in the future
$comment->project_id = $project->id;
$comment->save();
return Redirect::back();
}
If you want to add a hidden field with the project ID to the form, you can access its value by calling $request->input('project_id');
I feel the above answer is far from perfect as you're not only exposing Unique ID's to users but it's also long winded, and would fail if two users were to load the same page at the same time, instead you should do
public function store(CommentsFormRequest $request )
{
$comment = new Note([
// your fields here
]};
$comment->save();
//$comment now contains a unique ID!
return redirect($comment->id);
}
You can get last id by using insertGetId() Query Builder method
If the table has an auto-incrementing id, use the insertGetId method to insert a record and then retrieve the ID:
$id = DB::table('users')->insertGetId(
['email' => 'john#example.com', 'votes' => 0]
);
for more info check document

Categories