View user name by id in laravel 5.2 - laravel

I have two table that I join in my controller.
Here is my controller :
$data = DB::table('classrooms')
->select('classrooms.id as classrooms_id', 'classrooms.*', 'joinclass.*')
->join('users', 'classrooms.user_id', '=', 'users.id')
->join('joinclass', 'classrooms.class_code', '=', 'joinclass.class_code')->get();
return View::make('std_classes')->with('data',$data);
In my joinclass table I have user_id. Now I want to view user name and that has in my users table. How can I select in this controller and view my blade page. I try this many time but I can't.
Here is my view:
Teacher: {{$data->name}}

Here, I added few modifications, You should try this in your controller
$data = DB::table('classrooms')
->join('users', 'classrooms.user_id', '=', 'users.id')
->join('joinclass', 'classrooms.class_code', '=', 'joinclass.class_code')
->select('users.name as name', 'classrooms.id as classrooms_id', 'classrooms.*', 'joinclass.*')
->get();
return view('std_classes',compact('data'));
And use following code on view to display records
#foreach($data as $stud)
{{$stud->name}}
#endforeach

You have to select it first then you could use it as $data->name, so try to add users.name to select :
$data = DB::table('classrooms')
->select('users.name as name', 'classrooms.id as classrooms_id', 'classrooms.*', 'joinclass.*')
->join('users', 'classrooms.user_id', '=', 'users.id')
->join('joinclass', 'classrooms.class_code', '=', 'joinclass.class_code')
->get();
return View::make('std_classes')->with('data',$data);
You could get the image also using :
->select('users.name as name','users.image as image', 'classrooms.id as classrooms_id', 'classrooms.*', 'joinclass.*')
Or get all users attributes in same time using users.* :
->select('users.*', 'classrooms.id as classrooms_id', 'classrooms.*', 'joinclass.*')
Hope this helps.

Related

How create a subquery with eloquent and laravel with softdeletes

I am using Laravel 7 and Vue.js 2.
I want to retrieve the tasks that are not assigned to a specific user.
I made the following code that works correctly.
$tasks_user = TaskUser::select('task_id')
->where('user_id', $id)
->get();
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', $tasks_user)
->distinct()
->get();
By the way to be more elegant I decided to transform the above code into a single query as follows:
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', function($q) use ($id)
{
$q->select('task_id')
->from('task_user')
->where('user_id', $id)
->get();
})
->distinct()
->get();
Unfortunately I discovered that the above query didn't work because it doesn't considers softdeletes.
For example, if the user with id 3 was related with the task 7 but now that row has been deleted with softdeletes in the table task_user, the first code returns also the task with id 7 (correctly) and the second one not (uncorrectly).
So finally, I must do a single query that works as the first code.
Can help?
You can actually combine both approaches. whereNotIn accepts also an Eloquent Query, it doesnt need to be a callback. Try this:
$userRelatedTasksQuery = TaskUser::select('task_id')
->where('user_id', $id);
$tasks = Task::select('tasks.id as id', 'tasks.name as name', 'tasks.description as description')
->join('task_user', 'tasks.id', '=', 'task_user.task_id')
->whereNotIn('task_user.task_id', $userRelatedTasksQuery)
->distinct()
->get();
Be sure to not use get() at the end of the $userReleatedTasksQuery, as you want the eloquent query instance, not the result.

Laravel join db query from subquery (mergebindings)

I have DB query like this :
$visitor = DB::table('visitor_anonymous')
->join('users', 'visitor_anonymous.host', '=', 'users.host')
->whereBetween('visitor_anonymous.created_at', [$startDate, $endDate])
->select(DB::raw('DATE(visitor_anonymous.created_at) AS date, COUNT(visitor_anonymous.host) AS visitor'))
->groupBy(DB::raw("DATE(visitor_anonymous.created_at)"));
$session = DB::table('visitor_anonymous')
->join('visitor_anonymous_pageviews', 'visitor_anonymous.session_id', '=', 'visitor_anonymous_pageviews.session_id')
->join('users', 'visitor_anonymous.host', '=', 'users.host')
->whereBetween('visitor_anonymous_pageviews.created_at', [$startDate, $endDate])
->select(DB::raw('DATE(visitor_anonymous_pageviews.created_at) AS date, COUNT(visitor_anonymous_pageviews.session_id) AS session'))
->groupBy(DB::raw("DATE(visitor_anonymous_pageviews.created_at), visitor_anonymous.session_id"));
$pageview = DB::table('visitor_anonymous')
->join('visitor_anonymous_pageviews', 'visitor_anonymous.session_id', '=', 'visitor_anonymous_pageviews.session_id')
->join('users', 'visitor_anonymous.host', '=', 'users.host')
->whereBetween('visitor_anonymous_pageviews.created_at', [$startDate, $endDate])
->select(DB::raw('DATE(visitor_anonymous_pageviews.created_at) AS date, sum(visitor_anonymous_pageviews.count) AS pageview'))
->groupBy(DB::raw("DATE(visitor_anonymous_pageviews.created_at)"));
Hope result like this but didn't work. How to join subquery like this ?
$table = DB::table( DB::raw("({$visitor->toSql()}) as v"))
->leftJoin(DB::raw("({$session->toSql()}) as s"), 'v.date','=','s.date')
->leftJoin(DB::raw("({$pageview->toSql()}) as p"), 'v.date','=','p.date')
->select(DB::raw('v.date, sum(visitor) AS visitor, sum(session) AS session, sum(pageview) AS pageview'))
->groupBy(DB::raw("v.date"))
->mergeBindings($visitor);
Please tell me, solution. Thanks

Messages: show User Name with variable User_ID

i have 2 tables, to create messages, conversation and messages. If you create a new message with a new partner, you get a new conversation ID, so if you started the conversation, your user_id is in the messages table and in the conversation table you are user_one your writting partner is user_two. But if somewhere else is started the conversation you are user_two and in the messages table, the user_id ist the other user.
I need the name from your writting partners to show in a list.
Example:
Mario / Last Message / -> if i click so i will see the messages
Maria / Last Message / -> if i click so i will see the messages
To save and show the messages is working. I need only to read the name from your conversation partner.
With my solution i get the name of the writting partners, but only if you are User two.
The problem is the join.
I need something like JOINNOTIN
My table:
Conversation
'id'
'user_one'
'user_two'
Messages
'id'
'message'
'userid'
'conversationid'
My Query:
$messages = DB::table('conversation')
->select('messages.message', 'conversation.user_one', 'conversation.user_two', 'users.name', 'users.firstname', 'messages.id', 'messages.created_at', 'conversation.id')
->join('users', 'users.id', '=', 'conversation.user_one')
->join('messages', 'messages.conversation_id', '=', 'conversation.id')
->where('messages.userid', '!=', Auth::user()->id)
->orwhere('conversation.user_one', '=', Auth::user()->id)
->orwhere('conversation.user_two', '=', Auth::user()->id)
->groupBy('messages.conversation_id')
->latest()
->get();
You need the condition user_one == auth()->user()->id OR user_two == auth()->user()->id in the join() method.
$authId = auth()->user()->id;
$messages = DB::table('conversation')
->select('messages.message', 'conversation.user_one', 'conversation.user_two', 'users.name', 'users.firstname', 'messages.id', 'messages.created_at', 'conversation.id')
->join('users', function ($join) use ($authId) {
$join->on('id', '=', 'user_one')->orOn('id', '=', 'user_two')
->where('id', '!=', $authId);
})
->join('messages', 'messages.conversation_id', '=', 'conversation.id')
->where('messages.userid', '!=', Auth::user()->id)
->orwhere('conversation.user_one', '=', Auth::user()->id)
->orwhere('conversation.user_two', '=', Auth::user()->id)
->groupBy('messages.conversation_id')
->latest()
->get();

Concatenate two field into a alias name laravel

$data = DB::table('tables')
->select('orders.order_id', 'users.*')
->leftJoin('lists', 'lists.order_id', '=', 'orders.order_id')
->leftJoin('users', 'users.user_id', '=', 'lists.user_id')
->where('users.type', '=', 'admin')
->get();
dd($data);
getting first_name and last_name how can i group those i.e alias says full_name
fullname => Max jones
Concatenate two field into a alias name laravel
used raw method laravel and mysql concat method used here
DB::raw("CONCAT(`users`.`first_name`,`users`.`last_name`) as full_name")
try
$data = DB::table('tables')
->select('orders.order_id', DB::raw("CONCAT(`users`.`first_name`,`users`.`last_name`) as full_name"))
->leftJoin('lists', 'lists.order_id', '=', 'orders.order_id')
->leftJoin('users', 'users.user_id', '=', 'lists.user_id')
->where('users.type', '=', 'admin')->get();
dd($data);
DB::raw("CONCAT('name','id') AS ID"))

laravel 404 error page , redirect

looking for some help, I'm fetching a survey and questions, from method, when select some survey by id, from a route. But when I delete a survey, and when writing in url like http://localhost/survey_details/27 ( 27 is survey Id , which not exist anymore), I'm getting not some expection or redirection or Page not found info, but getting error where undefined variable $dat. But I need some how to show 404 page not found, or just redirect to other page if id not exist. Can some one help me?
here is my route:
Route::get('survey_draft/{id}', 'SurveyController#editSurveyDraft');
Here is my controller:
public function viewSurvey($id)
{
$object = DB::table('question')
->where('survey_id', '=', $id)
->where('name', '!=', NULL)
->get();
$teamName = DB::table('survey')->where('surveyId', '=', $id)
->join('team', 'survey.teamId', '=', 'team.teamId')
->join('company', 'company.id', '=', 'team.companyID')
->get();
$company = Auth::user()->company;
$data = Survey::where('surveyId', '=', $id)->get();
$teams = Auth::user()->teams;
$checkUserTeam = DB::table('teammembersall')
->where('UserId', '=', Auth::user()->id)
->get();
$members = Survey::where('surveyId', '=', $id)
->join('team', 'team.teamId', '=', 'survey.teamId')
->join('teammembersall', 'teammembersall.TeamId', '=', 'team.TeamId')
->join('users', 'users.id', '=', 'teammembersall.UserId')
->select('users.*')
->whereNotExists(function ($query) use ($id) {
$query->select(DB::raw(1))
->from('answer')
->whereRaw('answer.answerAboutUserId = users.id')
->where('answer.surveyId', '=', $id)
->where('answer.member_id', '=', Auth::user()->id);
})
->get();
$questions = DB::table('answer')->get();
return view('survey_details', ['object' => $object, 'data' => $data, 'teams' => $teams, 'members' => $members, 'questions' => $questions, 'checkUserTeam' => $checkUserTeam, 'teamName' => $teamName, 'company' => $company]);
}
To solve your immediate issue, you could add one of these this after $object ... get() depending on your result. One of them should work.
if(empty($object)){ abort(404); }
or
if(!$object->count()){ abort(404); }
However, your code would be much simpler if you used 2 basic laravel technologies.
ORM instead of DB::...
Route model binding. (which would handle your 404 for you)
https://laravel.com/docs/5.6/eloquent
https://laravel.com/docs/5.6/routing#route-model-binding

Resources