protected function show()
{
$users = User::all();
$letters = Letter::with('user');
$userLetter = $letters->where(['user_id' => 2])->count();
//Here function work right. Shows that we have 10 users
foreach ($users as $user) {
$userLetter = $letters->where(['user_id' => $user->id])->first();
if($userLetter){
//Here it shows that only the first user exists, returns null for the rest users.
}
}
}
We get an error when we sort the array with foreach.
No record is found in the database except the first.
For other entries, return null.
outside foreach no errors.
Just move your object inside the loop like below.
protected function show()
{
$users = User::all();
$userLetter = $letters->where(['user_id' => 2])->count();
//Here function work right. Shows that we have 10 users
foreach ($users as $user) {
$userLetter = Letter::with('user')->where(['user_id' => $user->id])->first();
if($userLetter){
}
}
}
You would probably be better off using a letter relationship on the User.
On the User model you could do something like :
public function letter()
{
return $this->hasOne(Letter::class, 'user_id');
}
Then you could in the controller:
protected function show()
{
$users = User::with('letter')->get();
foreach ($users as $user) {
if ($user->letter) {
// do things
}
}
}
Related
I'm trying to store multi-data to my pivot table. I have CategoryUser table with category_id and user_id.
Store function
public function store(Request $request)
{
foreach ($request->userId as $key => $userId) {
$data = new CategoryUser();
$data->user_id = $userId;
$data->category_id = $request->categoryId[$key];
$data->save();
}
return redirect()->back();
}
In my Blade file i have name="categoryId[]" and name="userId[]".
However, it stores only one category_id. What am I doing wrong?
For 1 user ID case, loop through category ID array first.
public function store(Request $request)
{
foreach ($request->categoryId as $key => $categoryID) {
$data = new CategoryUser();
$data->user_id = $request->userId[0];
$data->category_id = $categoryID[$key];
$data->save();
}
return redirect()->back();
}
I am using laravel 5.4 and I want to filter search. its my front-end
my code looks like this
class DeviceFilterController extends Controller
{
public function filter(Feature $feature){
$marks = isset($_POST["mark"]) ? $_POST["mark"] : null;
$feature = $feature->newQuery();
if(isset($marks ))
{
foreach ($marks as $value)
{
$feature->where('device_mark', $value);
}
}
return $feature->get();
}
}
that result just one entry
You could take a different approach using whereIn(), assuming you mark input is an array of IDs like [1, 4, 8, 22].
public function filter(Request $request)
{
$features = Feature::when($request->has('mark'), function($query) use ($request) {
return $query->whereIn('device_mark', $request->mark); //Assuming you are passing an array of IDs
})->get();
return $features;
}
when() closure will only executes when you are sending 'mark' input. Doing it without when would look like this
public function filter(Request $request)
{
$features = [];
if ( $request->has('mark') && $request->mark != '' ) {
$features = Feature::whereIn('device_mark', $request->mark)->get();
} else {
$features = Feature::get();
}
return $features;
}
I have 2 many to many relationships and trying to get all related data.
User model:
public function roles()
{
return $this->belongsToMany('App\Role', 'user_role_pivot', 'user_id', 'role_id');
}
Role model:
public function rolepermissions()
{
return $this->belongsToMany('App\RolePermission', 'role_permissions_connect', 'role_id', 'role_perm_id');
}
I'm making policies and want to get all values from my rolepermissions.
my policy:
public function createrole(User $user)
{
foreach ($user->roles as $role) {
foreach ($role->rolepermissions as $permission) {
return $permission->permission_name;
}
}
}
It only returns only one result, but i want to get all related data from role permissions.
As soon as a function hits return, it stops to execute and returns the result. It's different than for example yield return in C# where you can actually return multiple values.
Anyways, You might want to add everything to an array and then use your array to execute actions, like this:
public function createrole(User $user) {
$array = [];
foreach ($user->roles as $role) {
foreach ($role->rolepermissions as $permission) {
array_push($array, $permission);
}
}
dd($array); //add this line if you want to see your array's items
foreach($item in $array){
//do something
}
}
Now that we're doing best practices anyways, you can also do this:
foreach ($user->roles as $role) {
foreach ($role->rolepermissions as $key => $permission) {
$array[$key] = $permission;
}
}
Which is performance-wise probably more efficient.
You're returning $permission->permission_name
so the return forces the function to stop executing. You're better off returning an array.
$roles = [];
foreach ($user->roles as $role) {
foreach ($role->rolepermissions as $permission) {
$roles[] = $permission->permission_name;
}
}
}
return $roles;
In my app admin users can create articles. Articles table is: ID | user_id | title ...
For every Article other user (which not admin) can post an offer and Offer table is: ID | user_id(not admin) | article_id | price ...
Now I need to get all users for an admin user which post Offer to their Article... I try:
public function userbase()
{
$id = Auth::user()->id;//get admin id
$articles = Article::where('user_id', $id)->get();//select all admin articles
foreach ($articles as $article) {
$users = Offer::where('article_id', $article['id'])->orderBy('created_at', 'desc')->get(); //get all admin users
}
return $users;
}
but I get just: []
also my Model is:
Article:
public function offers() {
return $this->hasMany('App\Offer');
}
Offer:
public function user() {
return $this->belongsTo('App\User');
}
public function article() {
return $this->belongsTo('App\Article');
}
So how I can get all user details which was posted offer to an admin user?
UPDATE
I also try this:
$articles = Article::with([
'offers' => function($query) {
$query->orderBy('created_at', 'desc');
$query->with('user'); // if you want to eager load users for each offer too...
}
])->where('user_id', Auth::id())->get();
and I get this data:http://i.imgur.com/0kBVGrx.png
but how to access user data? I try ->get('user') but dont work...
2. UPDATE:
I also try:
public function userbase()
{
$articles = Auth::user()->articles()->get();
foreach ($articles as $article) {
$offers = Offer::where('article_id', $article['id'])->orderBy('created_at', 'desc')->get();
}
foreach ($offers as $offer) {
$users = User::where('id', $offer['user_id'])->orderBy('created_at', 'desc')->get();
}
return $users;
}
but I get undefined variable users
Try this :
First, you may add an attribute 'isAdmin' in your User model.
public function userbase()
{
return Offer::select('users.*')
->where('users.isAdmin', false)
->join('articles','articles.id','=','offers.article_id')
->join('users','users.id','=','articles.user_id')
->where('articles.user_id', Auth::user()->id)
->orderBy('offers.created_at', 'desc')
->groupBy('users.id')
->get();
}
Updating Your solution :
public function userbase()
{
$articles = Auth::user()->articles;
foreach ($articles as $article) {
$offers = Offer::where('article_id',$article->id)->orderBy('created_at', 'desc')->get();
}
$users = array();
foreach ($offers as $offer) {
$users[] = User::where('id', $offer['user_id'])->orderBy('created_at', 'desc')->get();
}
return $users;
}
i have two tables users its model (User) ... and servs it model (servs) .... the relation is one to many .... when i try to select all sevices with belong to one user .... it select first service only and ignore others ... this is code i used it
public function getserv(){
return View::make('infos.serv');
}
public function postserv(){
$user = User::find(Auth::user()->id);
$user_id = $user->id;
$serv = servs::where('user_id','=',$user_id);
if($serv->count()){
$serv = $serv->get();
//return $serv->user_id;
foreach ($serv as $servs) {
return $servs->serv_id;
}
}
}
Instead of returning the data at the first loop, you should better do something like this:
$result = array();
foreach ($serv as $servs) {
$result[] = $servs->serv_id;
}
return $result;
Try this.
public function postserv(){
$user = User::find(Auth::user()->id);
$user_id = $user->id;
$serv = servs::where('user_id','=',$user_id)->get()->first;
if($serv)
return $serv->serv_id;
else
return null;
}
You only see the first one because when you return something the function ends and the rest of $serv doesn't get processed.
I recommend you first set up Eloquent relations properly
class User extends Eloquent {
public function servs(){
return $this->hasMany('servs');
}
}
After that you can retrieve all servs for a user like this:
$user = Auth::user();
$servs = $user->servs;
foreach ($servs as $serv) {
echo $serv->serv_id;
}