Search query through foreign key - laravel

I'm trying to search through my comments on the username connected to the user_id Foreign Key
Tables:
Comment- id, comment, user_id, timestamps
User - id, name, username
Models:
class Comment extends Model
{
public function author()
{
return $this->belongsTo('App\User','user_id');
}
}
Controller:
public function index(Request $request)
{
$comments = Comment::query()->orderby('created_at', 'DESC');
$id=$request->]
return view('comments.index')->withComment($comment);
}
View:
<div class="panel-body">
{!! Form::open(['route' => 'comments.index', 'method' => 'GET']) !!}
<div class="col-md-5">
{!! Form::label('id', 'Search By ID:') !!}
{!! Form::text('id', null, array('class' => 'form-control')) !!}
</div>
<div class="col-md-5">
{!! Form::label('username', 'Search By Username:') !!}
{!! Form::text('username', null, array('class' => 'form-control')) !!}
</div>
<div class="col-md-2">
{!! Form::submit('Find Comments', array('class' => 'btn btn-send ')) !!}
</div>
{!!Form::close()!!}
</div>
#foreach($comment as $comments)
//data
#endforeach

I believe it is failing at the builder level because you are trying to query on an object that is not yet known. IE the author LIKE must be part of a sub query:
$comments = Comment::whereHas('author', function ($query) use($request) {
$query->where(users.username, 'LIKE', $request->input('username') )
}])->orderby('created_at', 'DESC')->get();
I see you will have to write the query a second time, but I think this may be successful for you.

Related

how to Checked if value of static checkboxes are equal on what you have in your database in Laravel

I have this column in my database named "source_income"
Which was Imploded from my EDIT page.
Problem is after I save the record, I see all the checkboxes are checked. I understand that the cause of the problem is that I do not have something that will check if the value of the checkbox should be equal to what I have in the database.
The checkboxes on my form are not dynamic.
<div class="col-md-6 ">
<div class="form-group {{ $errors->has('source_income') ? 'has-error' : ''}}">
<strong>Check all that apply to you:</strong>
<br>
<br>
{!! Form::checkbox('source_income[]', 'employed', null, ['id' => 'employed']) !!}
{!! Form::label('employed', 'Employed') !!}
<br>
{!! Form::checkbox('source_income[]', 'online-seller', null, ['id' => 'online-seller']) !!}
{!! Form::label('online-seller', 'Online Seller') !!}
<br>
{!! Form::checkbox('source_income[]', 'rider', null, ['id' => 'rider']) !!}
{!! Form::label('rider', 'Rider (Grab,Lazada,Etc.)') !!}
<br>
{!! Form::checkbox('source_income[]', 'small-business-owner', null, ['id' => 'small-business-owner']) !!}
{!! Form::label('small-business-owner', 'Small Business Owner') !!}
<br>
{!! Form::checkbox('source_income[]', 'no-income', null, ['id' => 'no-income']) !!}
{!! Form::label('no-income', 'No income') !!}
<br>
{!! Form::checkbox('source_income[]', 'remittances-allotment', null, ['id' => 'remittances-allotment']) !!}
{!! Form::label('remittances-allotment', 'Remittances / Allotment') !!}
{!! $errors->first('source_income', '<p class="help-block">:message</p>') !!}
</div>
</div>
EDIT,BLADE.PHP
public function edit($id, Profile $model)
{
$user_id = Auth::user()->id;
$user = User::findOrFail($user_id);
$profile = Profile::findOrFail($id);
$profileSourceIncome = explode(",", $profile->source_income);
return view('dashboard.profile.edit', compact('model','profile'))
->with('user', $user)
->with('profileSourceIncome', $profileSourceIncome);
}
I literally stopped in this part $profileSourceIncome = explode(",", $profile->source_income);
My question is how can I able to display the checkboxes checked if the name of the checkbox is equal to any value from $profileSourceIncome[]?
Thank you so much in advance!
According to the documentation, you only need to pass true as the third parameter in your Form::checkbox(...) calls to return a checkbox that is already checked.
public function edit($id, Profile $model)
{
$user_id = Auth::user()->id;
$user = User::findOrFail($user_id);
$profile = Profile::findOrFail($id);
// Turn this array into a Collection
$profileSourceIncome = collect(explode(',', $profile->source_income));
return view('dashboard.profile.edit', compact('model','profile'))
->with('user', $user)
->with('profileSourceIncome', $profileSourceIncome);
}
And then, in your blade file, you could use the Collection's contains() method to do the following:
Form::checkbox('source_income[]', 'employed', $profileSourceIncome->contains('employed'), ['id' => 'employed'])
Form::checkbox('source_income[]', 'online-seller', $profileSourceIncome->contains('online-seller'), ['id' => 'online-seller'])
Form::checkbox('source_income[]', 'rider', $profileSourceIncome->contains('rider'), ['id' => 'rider'])
Form::checkbox('source_income[]', 'small-business-owner', $profileSourceIncome->contains('small-business-owner'), ['id' => 'business-owner'])
Form::checkbox('source_income[]', 'no-income', $profileSourceIncome->contains('no-income'), ['id' => 'no-income'])
Form::checkbox('source_income[]', 'remittances-allotment', $profileSourceIncome->contains('remittances-allotment'), ['id' => 'remittances-allotment'])

Laravel 5.2, carry over article ID to next page and insert into database field

I am trying to use Laravel 5.2 to add questions to an article. Currently I can edit the article, using the edit function in the ArticleController. I want to have a button on the Article edit view, that allows the user to add a question. So when this is clicked, I need it to take the user to /articles/questions/create, but it needs to bring the ID for the article it has just come from with it, so it can be automatically stored in the article_id field in the db table. How would I do this, currently I can store the article ID by manually typing the in a text box on the creation form. Obviously, the aim is for the user to not have to know the ID of the article, and for it to be added automatically.
My Create function so far:
public function create(){
$questions = Question::all();
$users = User::all();
$articles = DB::table('article')->where('id', 'article_id')->get();
return view('articles/questions/create', ['question' => $questions], ['users' => $users], ['article' => $articles]);
}
The form so far:
<h1>Create & Add Question</h1>
{!! Form::open(array('action' => 'QuestionController#store', 'id' => 'createquestion')) !!}
{{ Form::hidden(csrf_token()) }}
<div class="row col-sm-12 col-lg-12">
{!! Form::label('article_id', 'Article ID:') !!}
{!! Form::text('article_id', null, ['class' => 'large-8 columns']) !!}
</div>
<div class="row col-sm-12 col-lg-12">
{!! Form::label('title', 'Question:') !!}
{!! Form::textarea('title', null, ['class' => 'large-8 columns']) !!}
</div>
<div class="row col-sm-12 col-lg-12">
{!! Form::label('require', 'Required?') !!}
{{ Form::radio('require', 1) }} Yes <br>
{{ Form::radio('require', 0) }} No
</div>
<br>
<div class="row large-4 columns">
{!! Form::submit('Add Question', ['class' => 'button']) !!}
</div>
{!! Form::close() !!}
The form does successfully post the the Database, I just need the ID to automatically insert so that the article can reference it to show the question on the article page.
First of all edit the below lines
$articles = DB::table('article')->where('id', 'article_id')->get();
return view('articles/questions/create', ['question' => $questions], ['users' => $users], ['article' => $articles]);
to
$articles = DB::table('article')->where('id', 'article_id')->first();
return view('articles/questions/create', ['question' => $questions, 'users' => $users, 'article' => $articles]);
Now, take a hidden field in the form you posted above
{!! Form::hidden('article_id', $article->id) !!}
and finally access the article id in your store method.
public function store(Request $request){
$article_id = $request->article_id
}

update user avatar with laravel5

From the look of it seems to me very logic but I am missing something, it doesn't work, nothing changes!
Here is my profile controller file:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use Image;
class ProfileController extends Controller
{
public function profile()
{
$user = Auth::user();
return view('profile')->with('user', $user);
}
public function edit()
{
$user = Auth::user();
return view('edit')->with('user', $user);
}
public function update(Request $request)
{
if($request->hasFile('avatar'))
{
$avatar = $request->file('avatar');
$filename = time().'.'.$avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 300)->save(public_path('/uploads/users_avatars/'.$filename));
$user = Auth::user();
$user->avatar = $filename;
$user->save();
}
return redirect('profile')->with('user', Auth::user());
}
}
and here is my edit.blade.php
#extends('layouts.app')
#section('content')
<div class="col-md-6">
{!! Form::model($user, ['method'=>'PATCH', 'action'=>'ProfileController#update', 'file'=>'true']) !!}
<div class="form-group">
{!! Form::label('name', 'Name') !!}
{!! Form::text('name', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('email', 'Email') !!}
{!! Form::email('email', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('number', 'Phone') !!}
{!! Form::text('number', null, ['class'=>'form-control']) !!}
</div>
<div class="form-group col-md-5">
{!! Form::label('avatar', 'Avatar') !!}
{!! Form::file('avatar', ['class'=>'form-control']) !!}
</div><br><br><br><br>
<div class="form-group">
{!! Form::submit('Update', null, ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
</div>
#stop
but when I edit the user it doesn't change..plz help
It seems like you have made a mistake while using Form from Laravel HTML Collective. You should use "files" => true instead of "file" => true
{!! Form::model($user, ['method'=>'PATCH', 'action'=>'ProfileController#update', 'file'=>'true']) !!}

storing data with name of author - laravel 5.2

I have hasMany relation to my model user and reports.
I want to set author name for the reports. (Like a blog-post author)
my model User:
public function reports() {
return $this->hasMany('App\Report', 'author_id');
}
model Report
public function user() {
return $this->belongsTo('App\User', 'author_id');
}
and my controller:
public function create()
{
$category = Category::lists('title','id');
return view('dash.reports.create')->with('category', $category);
}
/**
* Store a newly created resource in storage.
*
* #return void
*/
public function store(Request $request)
{
$this->validate($request, ['title' => 'required', ]);
Report::create($request->all());
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}
I'm able to set in in phpmyadmin, but how can i set it with my controller?
edit: my view:
{!! Form::open(['url' => '/dash/reports', 'class' => 'form-horizontal']) !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('title', 'Servizio', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::text('title', null, ['class' => 'form-control', 'required' => 'required']) !!}
{!! $errors->first('title', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
{!! Form::label('date', 'Data lavorativa', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-2">
{!! Form::selectRange('day', 1, 31, null, ['class' => 'form-control']) !!}
{!! $errors->first('day', '<p class="help-block">:message</p>') !!}
</div>
<div class="col-sm-2">
{!! Form::selectMonth('month', null, ['class' => 'form-control']) !!}
{!! $errors->first('month', '<p class="help-block">:message</p>') !!}
</div>
<div class="col-sm-2">
{!! Form::select('year', array('2016' => '2016', '2015' => '2015'), null, ['class' => 'form-control']) !!}
{!! $errors->first('year', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group {{ $errors->has('category_id') ? 'has-error' : ''}}">
{!! Form::label('category_id', 'Cliente', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-6">
{!! Form::select('category_id', $category, null, ['class' => 'form-control'] ) !!}
{!! $errors->first('category_id', '<p class="help-block">:message</p>') !!}
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-3">
{!! Form::submit('Create', ['class' => 'btn btn-primary form-control']) !!}
</div>
</div>
{!! Form::close() !!}
Very easy. Replace Report::create... with this.
$user = Auth::user();
$report = new Report($request->all());
$report->author()->associate($user);
$report->save();
Make sure you use Auth; up at the top.
This uses the Auth object to get the current user,
Builds a new Report using the $request data without saving,
Tells the report we're associating $user as the author for the model,
Saves the report with the authorship information.
solution:
public function store(Request $request)
{
$this->validate($request, ['title' => 'required', ]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$report->save();
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}

Update data with Laravel Collective forms

I have an edit form with Laravel Collective but when clicking the button, the data do not update. Below are my codes.
Form:
{!! Form::model($post, ['route' => ['/post/update/', $post->id]]) !!}
{{ method_field('PATCH') }}
<div class="form-group">
<div class="row">
<div class="col-lg-6">
{!! Form::label('title', 'Title') !!}
{!! Form::text('title', null, ['class' => 'form-control']) !!}
</div>
<div class="col-lg-6">
{!! Form::label('category_id', 'Category') !!}
{!! Form::select('category_id', $categories, null, ['class' => 'form-control']) !!}
</div>
</div>
</div>
<div class="form-group">
{!! Form::label('content', 'Content') !!}
{!! Form::textarea('content', null, ['class' => 'form-control', 'rows' => 10]) !!}
</div>
<hr/>
<div class="form-group">
{!! Form::submit('Update', ['class' => 'btn btn-success pull-right']) !!}
</div>
{!! Form::close() !!}
Controller:
public function edit($id)
{
return \View::make('admin/post/edit')->with([
'post' => \DB::table('posts')->find($id),
'categories' => \App\Category::lists('category', 'id')
]);
}
public function update(Request $request, Post $post)
{
$post->update($request->all());
return \Redirect::to('/admin/posts');
}
Routes:
Route::get('/admin/post/edit/{id}', 'Admin\PostController#edit');
Route::patch('/post/update/', [
'as' => '/post/update/',
'uses' => 'Admin\PostController#update'
]);
It's a bit different from the Laracast, and it's confusing me. Framework is new to me and the lack of code to do something is confusing.
I solved it. Mass Assignment. explains what to do if using update or create
So, the update method is:
public function update(Request $request, Post $post)
{
$post->title = $request->title;
$post->category_id = $request->category_id;
$post->content = $request->content;
$post->save();
return \Redirect::to('/admin/posts');
}

Resources