Laravel displaying the message for a specific person - php

I've made this project using the messages panel, and I want to display the message for a specific person. My relations:
In user:
public function Message()
{
return $this->belongsToMany('App\Message');
}
In message:
public function user()
{
return $this->belongsTo('App\User');
}
And in my controller its look like:
public function wiadomosci()
{
$menuClasses = ['', '', '', 'active', ''];
$messages = Message::where('to_id','=', Auth::user()->id);
return view('panel.wiadomosci', compact('menuClasses'))->with('messages', $messages);
}
When I add where in $message it does not display anything to me, but when I delete it, it shows me all of the messages not assigned to that user.
##Everything is fine now, problem solved. But I have a new problem: I would like to display the user name who send message(teacher_name) in the view, but I can only display an Id. controller:
public function wiadomosci()
{
$menuClasses = ['', '', '', 'active', ''];
$messages = Message::where('to_id','=', Auth::user()->id)
->join('teachers', 'messages.from_id', '=','teachers.id')
->get();
return view('panel.wiadomosci', compact('menuClasses'))->with('messages', $messages);
}
and in view :
#foreach($messages as $message)
Od:{{$message->teachers_name}}
</br>
Tytuł:{{$message->title}}
</br>
opis:{{$message->contents}}
</br>
#endforeach
In mysql query would look like this :
SELECT teachers.name FROM messages JOIN teachers ON messages.from_id=teachers.id

Related

Weird Problem: Trying to get property 'name' of non-object in Laravel Blade

I have four tables: users, countries, regions and townships.
In User.php model,
public function country() {
return $this->belongsTo(Country::class, 'country_id');
}
public function region() {
return $this->belongsTo(Region::class, 'region_id');
}
public function township() {
return $this->belongsTo(Township::class, 'township_id');
}
In Country.php, Region.php and Township.php models,
public function users() {
return $this->hasMany(User::class);
}
In users.blade, I tried to print user's location
{{ $user->township->name }}, {{ $user->region->name }}, {{ $user->country->name }}
and, I got Trying to get property 'name' of non-object exception.
When I just tried to print country, region and township like {{ $user->township->name }}, {{ $user->region->name }}, {{ $user->country->name }}, it printed as below -
{"id":1,"region_id":1,"name":"Hlaing"}, {"id":1,"country_id":1,"name":"Yangon"}, {"id":1,"name":"Myanmar"}
It gets this exception in remote server only, there is no problem in local machine.
I have three views for all users, approved users and pending users. I have users.blade.php, users_approved.blade.php and users_pending.blade.php. Those blades are similar with only title text difference. There is no problem in approved users view (remote server also).
In MainController.php, I have those functions -
function users(Request $request) {
$users = User::all();
return view('users', [ 'users' => $users ]);
}
function users_approved(Request $request) {
$users = User::where('approval_status', 'APPROVED')->get();
return view('users_approved', [ 'users' => $users ]);
}
function users_pending(Request $request) {
$users = User::where('approval_status', 'PENDING')->get();
return view('users_pending', [ 'users' => $users ]);
}
I have already tried - php artisan view:clear, php artisan cache:clear, php artisan config:clear.
If your problem occurs only on remote machine, maybe it's because the data stored there is different. In particular, for some users for some reasons (legacy records, code errors, not using transactions... etc.) some of their relations might just not be set.
One workaround, suggested on Eloquent docpage itself, is supplying default values for those tied models, used when relationship is missing in DB. For example:
public function country() {
return $this->belongsTo(Country::class, 'country_id')->withDefault([
'name' => 'Country Not Set',
])
}
public function region() {
return $this->belongsTo(Region::class, 'region_id')->withDefault([
'name' => 'Region Not Set',
])
}
... etc. Another option is running a DB query to fetch all the users on remote maching with the following condition:
WHERE country_id IS NULL
OR region_id IS NULL
OR township_id IS NULL
Depending on what you need, you may either modify those records or disable them in one way or another.

Laravel: User & Post Relationship

Model Structure
user.php
public function inventories() {
return $this->belongsToMany('App\Model\user\inventory')->orderBY('created_at','DESC')->paginate(10);
}
inventory.php
public function users() {
return $this->belongsToMany('App\Model\user\user')->withTimestamps();
}
Table Structure:
inventories:
id
user_id
content
users:
id
name
email
How to call the inventories->user_id to connect in users->id in controller?
Example in laravel blade:
user_id = 1
content = 'This is content'
I want is:
user_id = 'Name of user 1'
content = 'This is content'
Since you have defined your relations, you can use :
$inventories = Inventory::all();
foreach ($inventories as $inventory) {
foreach ($inventory->users as $user) {
echo $user->name; // show the name of user
}
// or to get first user :
$user_1_name = isset($inventory->users[0]) ? $inventory->users[0]->name : '-';
}
On your controller:
$inventories = Inventory::all();
On your blade file:
#foreach ($inventories as $inventory)
{{ $inventory->users()->id }}<br/>
#endforeach

Search all method missing where argument in Laravel 5

I'm trying to write a method in my controller to allow searching the results of my query on my view page. The query selects all results from the "ads" table and this method should allow filtering results by the ad's name inputting keywords in the search bar.
The controller code goes like this:
public function index(Request $request)
{
$title = trans('ad.title');
$ads = Ad::paginate(10);
if (!empty($request->input('search_all'))) {
$search_all = urldecode($request->input('search_all'));
$ads->where(function ($query) use ($search_all) {
$query->where('name', 'like', '%'.$search_all.'%')->get();
});
}else {
// Returning to view
return view('admin.ad.list')
->with('ads', $ads)
->with('title', $title);
}
}
However, when I run a search I get the following error: "Missing argument 2 for Illuminate\Support\Collection::where()".
What am I doing wrong?
At the top, when doing $ads = Ad::paginate(10); you have already pulled the results from the database so no more filtering can be done at DB level.
I'd do something like this instead:
public function index(Request $request)
{
$title = trans('ad.title');
$ads = Ad::select();
if ($request->input('search_all')) {
$search_all = urldecode($request->input('search_all'));
$ads->where('name', 'like', '%'.$search_all.'%');
}
// Returning to view
return view('admin.ad.list')
->with('ads', $ads->paginate(10))
->with('title', $title);
}

Laravel save relation from input

I have the following relations:
Ticket Model:
public function status()
{
return $this->belongsTo('App\Status');
}
Status Model:
public function tickets()
{
return $this->hasMany('App\Ticket');
}
TicketController function create()
$statuses = Status::get()->lists('name', 'id');
return view('backend.tickets.create', compact('statuses'));
View create.blade.php
{!! Form::select('status', $statuses, null, ['class' => 'form-control']) !!}
TicketController function store()
// Get the selected status from input and find the Status
$status = Status::where('id', '=', $request['status'])->first();
// Associate status to ticket
$ticket->status()->associate($status);
It does not work. In the database the status_id in my ticket table is always null.
Can you help me?
Thank you!
After the association, you should save the $ticket:
// Get the selected status from input and find the Status
$status = Status::where('id', '=', $request['status'])->first();
// or better
$status = Status::find($request['status']);
// Associate status to ticket
$ticket->status()->associate($status);
// Save the ticket
$ticket->save();

Laravel 4 Creating Form for adding record with relationship

I have created very basic Model. I have persons table and emails table.
Also I have create a link in the persons/show.blade.php ("Add mail").
My models are
class Person extends Eloquent {
protected $table = 'persons';
public function email()
{
return $this->HasMany('Email');
}
}
and
class Email extends Eloquent {
protected $table = 'emails';
public static $rules = array(
'email'=>'required|unique:emails'
);
public function person()
{
return $this->belongsTo('Person');
}
}
How can I pass the $person->id to the new Controller?
In my show.blade.php for Person I added
{{ HTML::linkRoute('email.adduseremail','Προσθήκη Email',array($person->id))}}
and I added to my EmailController
public function adduseremail($id)
{
return View::make('email.createforuser',['id'=>$id]);
}
public function storeforuser($pid)
{
$validator = Validator::make(Input::all(),Email::$rules);
if ($validator->fails()) {
$messages = $validator->messages();
foreach ($messages->all('<li>:message</li>') as $message)
return Redirect::back()->withInput()->WithErrors($messages);
}
$person = Person::FindorFail($pid);
$email = new Email;
$email->email = Input::get('email');
$email->person()->associate($person);
$email->save();
return Redirect::route('person.index');
}
and my createforuser view is
<p>
{{Form::open(['route'=>'email.storeforuser'])}}
<div>
{{Form::label('email', 'Email:')}}
{{Form::input('text', 'email')}}
{{$errors->first('email')}}
</div>
</br>
<div>
{{Form::submit('Submit')}}
</div>
{{Form::close()}}
<p>
I keep getting Trying to get property of non-object (View: /var/www/laravel/app/views/email/show.blade.php)
Is there any example using Form and Models for inserting new objects to the database for 'belongsTo' Relationship? I couldn't find anything complete , just partial examples.
I generally use laravel sessions or laravel cache to tempererally save an id that i need to use later like:
Session::set('personId',$person->id);
Session::get('personId');
The same is for cache except cache will only last for the current request session is persistent for the session
Hope that helps
I am no sure if I 'm supposed to answer my own question but finally I found a solution.
I set two new routes
Route::post('email/adduseremail/{pid}', array('uses'=>'EmailController#adduseremail','as' => 'email.adduseremail'));
Route::post('email/storeforuser/{pid}', array('uses' =>'EmailController#storeforuser','as' => 'email.storeforuser'));
and created the corresponding methods in my Controller
public function adduseremail($id)
{
$pname = Person::Find($id)->name;
$psurname = Person::Find($id)->surname;
return View::make('email.createforuser',array('id'=>$id,'name'=>$pname, 'surname'=>$psurname));
}
and
public function storeforuser($pid)
{
$validator = Validator::make(Input::all(),Email::$rules);
if ($validator->fails())
{
$messages = $validator->messages();
foreach ($messages->all('<li>:message</li>') as $message)
return Redirect::back()->withInput()->WithErrors($messages);
}
$person = Person::FindorFail($pid);
$email = new Email;
$email->email = Input::get('email');
$email->person()->associate($person);
$email->save();
return Redirect::route('person.show',array($person->id));
}
then on my view blade pages I can pass the parameters from View to Form and so on
person.show.blade.php
{{Form::Open(array('route' => array('email.adduseremail', $person->id),'method' => 'POST','style'=>'display:inline;'))}}
{{Form::submit('Add Email')}}
{{Form::close()}}
and
email.createforuser.blade.php
{{Form::open(array('route'=>array('email.storeforuser',$id),'method' => 'POST','style'=>'display:inline;'))}}
{{Form::label('email', 'Email:')}}
{{Form::input('text', 'email')}}
{{Form::submit('Submit')}}
Hope it helps others also

Categories