How to get user name from another table in laravel - laravel

Hello I want to get user names on my reply table, but there its shows me only user id, when I type $reply->user_id->name it shows me that error: "Attempt to read property "name" on int".
How can I fix it ?
there are my codes:
Ticket Model
public function replies() {
return $this->hasMany(Reply::class);
}
Reply Model
public function tickets() {
return $this->belongsTo(Tickets::class);
}
Tickets Controller
public function show($id) {
$user = Auth::user();
$tickets = Tickets::with('companies')->get();
$ticketscomp = Companies::with('tickets')->get();
$severities = Severities::with('tickets')->get();
$users = User::with('tickets')->get();
//$replies = DB::table('replies')->where('ticket_id', $id)->get();
// $articles = Reply::where('user_id', $id)->with('User')->get();
$ticketspage = Tickets::with('severities')->with('companies')->with('user')->with('replies')->findOrFail($id);
return view('tickets.ticket', compact('ticketspage'))->
with(['tickets'=> $tickets])->
with(['ticketscomp'=>$ticketscomp])->
with(['severities'=>$severities])->
with(['ticketspage'=>$ticketspage])->
with(['replies'=>$replies]);
//dd($reply_author->toArray());
}
Blade
#foreach ($replies as $reply)
<div class="NjBSH">
<div id="AuthorAndDate-1">
<span class="author">{{ $reply->user_id->name }}</span>
<span class="date"><span style="color: rgb(32, 33, 36);">{{ $reply->created_at }}</span><br></span>
</div>
<div class="kmSodw">
<span>{{ $reply->text }}</span>
</div>
</div>
#endforeach
Text, Created at showing also $reply->user_id but not this $reply->user_id->name.

Here is a complete solution using ELOQUENT:
Ticket Model
public function replies() {
return $this->hasMany(Reply::class);
}
Reply Model
public function ticket() {
return $this->belongsTo(Ticket::class);
}
public function user() {
return $this->belongsTo(User::class);
}
Tickets Controller:
public function show(Ticket $ticket) {
//Load all of the ticket relationships that we will be using
$ticket->load('replies.articles', 'replies.user', 'companies', 'severities');
//Assign the loaded ticket companies
$companies = $ticket->companies;
//Assign the loaded ticket severities
$severities = $ticket->severities;
//Assign the loaded ticket replies
$replies = $ticket->replies;
/*
You can acess the replies -> articles && user in a foreach loop, in php or blade
foreach($replies->articles as $article){
//$article->id
}
*/
return view('tickets.ticket', compact('ticket', 'companies', 'severities', 'replies'));
}
Blade
#foreach ($replies as $reply)
<div class="NjBSH">
<div id="AuthorAndDate-1">
<span class="author">{{ $reply->user->name }}</span>
<span class="date"><span style="color: rgb(32, 33, 36);">{{ $reply->created_at }}</span><br></span>
</div>
<div class="kmSodw">
<span>{{ $reply->text }}</span>
</div>
</div>
#endforeach

Related

Laravel 8 form select option dropdown problem

Am having problem here
I have two tables
Department table
with fields
id dept_code dept_name
I also have Persons table
with fields
id Persons_names Dept_name Position_held
I have a data entry form to enter data to the Persons_table
the problem am having is I want to create select option to get Dept_name From Department_table but am always getting undefined value error.
this is my form
{!! Form::open(['url' => 'persons_form/store']) !!}
{{ csrf_field() }}
<div class="form-row">
<div class="form-group col-md-6">
{{Form::label('FullNames', 'Fullnames')}}
{{Form::text('names', '',['class'=>'form-control','placeholder'=>'Persons Fullnames'])}}
</div>
<div class="form-group col-md-6">
{{Form::label('Department', 'Department')}}
#foreach ($depts as $dept)
{{
Form::select('department', $dept->department_name, null, ['class'=>'form-control','placeholder' => 'Select Department'])
}}
#endforeach
</div>
<div class="form-group col-md-12">
{{Form::label('Position', 'Position')}}
{{Form::text('level', '',['class'=>'form-control','placeholder'=>'Departmental Position'])}}
</div>
</div>
<div>
{{Form::submit('Save Data',['class'=>'btn btn-outline-primary text-center',])}}
</div>
{!! Form::close() !!}
this is my personsController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Models\People;
class PeopleController extends Controller
{
public function index()
{
$depts = DB::table('departments')->select('department_name')->get();
return view('strategic_plan.people_form', ['depts' => $depts]);
}
public function create()
{
$depts = DB::table('departments')->pluck('department_name');
}
public function store(Request $request)
{
$this->validate($request,[
'names'=>'required',
'department'=>'required',
'level' =>'required'
]);
$persons =new People;
$persons->names=$request->input('names');
$persons->department=$request->input('persons');
$persons->level=$request->input('level');
$dept->save();
return redirect('/people')->with('message','Person Added Succesifully');
}
public function show()
{
$persons = People::all()->sortByDesc("id");
return view('strategic_plan.people',compact('persons'));
}
public function edit($id)
{
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
When I try to open the Form am getting
$depts is undefined
Try using compact, And get #dd in your blade of $depts and share the code.
Use
return view('strategic_plan.people_form', ['depts' => $depts]);
instead of
return view('strategic_plan.people_form', compact('depts');
write it down

how can I order a list dynamically in laravel?

I try for a todo-list to be able to order the list via a filter so that can i have the list for today the list for tomorrow or the list of the week so i made my task controller able to take request et via the design pattern reposiory i take the request to do the eloquent request :
controller tasks :
class TaskController extends Controller
{
private $taskRepository;
public function __construct(TaskRepository $taskRepository)
{
$this->taskRepository = $taskRepository;
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if(!empty($request)){
// dd($request);
$tasks = $this->taskRepository->all($request);
}else{
$tasks = $this->taskRepository->all();
}
return view('tasks.index', compact('tasks'));
}
}
taskrepository :
class TaskRepository implements RepositoryInterface
{
// model property on class instances
protected $task;
// Constructor to bind model to repo
public function __construct(Task $task)
{
$this->task = $task;
}
public function all(Request $request)
{
$sortBy = 'expired_at';
$order = Carbon::now();
$finish = null;
if($request)
{
if($request->has('today'))
{
$order = Carbon::today();
return Task::where($sortBy, $order)->get();
}
if($request->has('tomorow')){
$order = Carbon::tomorrow();
return Task::where($sortBy, $order)->get();
}
if($request->has('week'))
{
$order = Carbon::now()->startOfWeek();
$finish = Carbon::now()->endOfWeek();
return Task::whereBetween($sortBy, [$order, $finish])->get();
}
}else{
return Task::orderBy('order')->get();
}
}
to finish in my index i have form using the "get" method :
div>
<form action="{{ route('tasks.index') }}" class="flex justify-between items-center p-2">
<div>
<select name="orderByDate" id="">
#foreach(['today','tomorow', 'week'] as $orderDate)
<option value="{{ $orderDate }}">{{ ucfirst($orderDate) }}</option>
#endforeach
</select>
</div>
<div>
<button type="submit">Filter</button>
</div>
</form>
</div>
<ul class="my-5">
#foreach ($tasks as $task)
#if($task->order == 0)
<li class="flex text-red-600 justify-between p-2">
// task->name
// task-> date
// task-> edit
// task->delete
</li>
#else
<li class="flex justify-between items-center p-2">
// task->name
// task-> date
// task-> edit
// task->delete
</li>
#endif
#empty
<p>Pas de tâches aujourd'hui crée en une</p>
#endforelse
</ul>
#endsection
aparrently my foreach doesn't work with an array so if anyone have some lead to how should i approch this issue will be a live saver ?
Try this code for the repository function
public function all(Request $request)
{
$sortBy = 'expired_at';
$order = Carbon::now();
$finish = null;
if($request)
{
if($request->has('today'))
{
$order = Carbon::today();
return Task::query()->where($sortBy, $order)->orderBy($sortBy)->get();
}
if($request->has('tomorow')){
$order = Carbon::tomorrow();
return Task::query()->where($sortBy, $order)->orderBy($sortBy)->get();
}
if($request->has('week'))
{
$order = Carbon::now()->startOfWeek();
$finish = Carbon::now()->endOfWeek();
return Task::query()->whereBetween($sortBy, [$order, $finish])->orderBy($sortBy)->get();
}
}else{
return Task::query()->orderBy($sortBy)->get();
}
}

How to restrict edit only on data display in the index in laravel

I have a problem with my edit.blade.php. In the show view, I have restricted it only on the users' logged in as you can see in my controller
public function index()
{
$animal = Auth::user()->animals;
return view('farms.index', compact('animal'));
}
And my index view
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Farm Dashboard</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
You are logged in! {{ Auth::user()->name }}
<br>
Add animal
#foreach( $animal as $animal)
<div class="row">
<div class="col-2">{{ $animal->id }}</div>
<div class="col-4">{{ $animal->type->category }}</div>
<div class="col-4">{{ $animal->created_at }}</div>
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
#endsection
But I still have a problem if I change in my url the id number of an object of another user I can still edit and update.
What can I change in my controller to prevent that
public function show($id)
{
$animal = Animal::query()->findOrFail($id);
return view('farms.show', compact('animal'));
}
/**
* Show the form for editing the specified resource.
*
* #param $id
* #return void
*/
public function edit($id)
{
$type = Type::all();
$user = Auth::user();
$animal = Animal::query()->findOrFail($id);
return view('farms.edit', compact('animal', 'type', 'user'));
}
/**
* Update the specified resource in storage.
*
* #param $id
* #return void
*/
public function update($id)
{
$animal = Animal::query()->findOrFail($id);
$animal->update($this->validateRequest());
return redirect('farms/' . $animal->id)->with('message', 'Animal Details Updated');
}
You can follow this basic/easy method
For Show
public function show($id)
{
try {
$user = auth()->user();
$animal = Animal::where('user_id', $user->id)->findOrFail($id);
return view('farms.show', compact('animal'));
} catch(\Exception $ex) {
//return exception or any other page
abort(404, 'Not allowed');
//or return back()->withErrors(['Not allowed']);
}
}
For edit
public function edit($id)
{
try {
$type = Type::all();
$user = auth()->user();
$animal = Animal::where('user_id', $user->id)->findOrFail($id);
return view('farms.edit', compact('animal', 'type', 'user'));
} catch(\Exception $ex) {
//return exception or any other page
}
}
For update
public function update($id)
{
try {
$user = auth()->user();
$animal = Animal::where('user_id', $user->id)->findOrFail($id);
$animal->update($this->validateRequest());
return redirect('farms/' . $animal->id)->with('message', 'Animal Details Updated'); //use route for redirect instead of url
} catch(\Exception $ex) {
//return exception or any other page
}
}
Use try catch for exception
Make sure you defined that animal has user_id
or
You can also manage this functionality with relationship
Larave Eloquent relationship
For standard practice, you can use laravel gate policy
Laravel policy via model

Display tests for lessons who belong to Courses

I have Courses which has lessons, and each lesson has a test. I'm trying to display the test when a lesson is clicked.
I've created the models, controller and view and it doesn't seem to work.
Here is the model for the Lesson
public function course()
{
return $this->belongsTo(Course::class, 'course_id')->withTrashed();
}
public function test() {
return $this->hasOne('App\Test');
}
Here is the controller
public function show($id)
{
$course = Course::with( 'lessons')->with('activeLessons')->findOrFail($id);
$created_bies = \App\User::get()->pluck('name', 'id')->prepend(trans('global.app_please_select'), '');
$trainers = \App\User::get()->pluck('name', 'id');
// $test = \App\Test::where('course_id', $id)->get();
$lesson = \App\Lesson::where('course_id', $id)->get();
// $course_test = Course::with('tests')->findOrFail($id);
$user = User::find(1);
$user->name;
return view('admin.courses.showCourse', compact('course', 'test', 'lesson','course_test', 'previous_lesson', 'next_lesson','date', 'user'));
}
function view_tests($id)
{
$lessons = Lesson::findOrFail($id);
$lessons->test;
return view('admin.courses.test', compact('lessons'));
Here is the Route
Route::get('/test/{id}', 'EmployeeCoursesController#view_tests')->name('test.show');
And here is the Blade with the link to display the test
#foreach($course->activeLessons as $lesson)
<article class="lesson" >
<p></p>
<p></p>
{!! $loop->iteration!!}.
<div class="body" id="title"> {!!$loop->iteration!!}. <h4>{{ $lesson->title }}</div>
<p> {!! $lesson->short_description !!}</p>
<iframe width="420" height="315" src="{{ $lesson->video_link}}" frameborder="0" allowfullscreen></iframe>
</article>
#endforeach
The issue was on the test blade. The code works well.

Get the user name and comment with article id in Laravel

I have 3 tables users, comments, and articles. I have a route like this:
Route::get('/article/{id}', 'ArticlesController#view');
What I want is when I accessing that route I will get User Name and their comment in this article id.
so here's my view function in ArticlesController:
public function view($id){
$article = Article::with('comments')->find($id);
return view('front.single',compact('article'));
}
and here's my single.blade.php code:
<div class="single-grid">
#section('content')
<h1>{{ $article->title }}</h1>
<p>{{ $article->content }}</p>
#show
</div>
<div class="comment-list">
#foreach($article->comments as $comment)
<ul class="comment-list">
<div class="comment-grid">
<img src="/images/avatar.png" alt=""/>
<div class="comment-info">
<h4>{{ $comment->user->name }}</h4>
<p>{{ $comment->comment }}</p>
<h5>{{ $comment->created_at->diffForHumans() }}</h5>
Reply
</div>
<div class="clearfix"></div>
</div>
</ul>
#endforeach
</div>
I'm not sure what how to do it since it gives me error like this:
"Call to undefined relationship [comment] on model [App\User]."
I already define the relation in each model. here's my articles model:
public function comments(){
return $this->hasMany(Comment::class);
}
public function user(){
return $this->belongsTo(User::class);
}
My comment model:
public function article(){
$this->belongsTo(Article::class);
}
public function user(){
$this->belongsTo(User::class);
}
and here's my User model:
public function articles(){
return $this->hasMany(Article::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function publish(Article $article){
$this->articles()->save($article);
}
here's my table structure:
-users(id,name,email,password,remember_token,created_at,updated_at)
-comments(id,user_id,article_id,comment,created_at,updated_at)
-articles(id,user_id,title,content,created_at,updated_at)
so how can I can User Name just by using this route? thanks.
on Your Comment Model, You need to replace articles to article
public function article(){
$this->belongsTo(Article::class);
}
also, if you want to get user specific comments, than you need to change your controller action code from
$article = Article::with('user.comment')->find($id) to
$article = Article::with('user.comments')->find($id);
I think that your issue comes from the use of compact function : an array is passed to the view instead of an object.
Can you try it like this :
// Controller
public function view($id) {
$article = Article::findOrFail($id);
return view('front.single', $article);
}
<!-- View -->
#foreach($article->comments as $comment)
{{ $comment->user->name }}
{{ $comment->comment }}
{{ $comment->created_at->diffForHumans() }}
#endforeach

Resources