Laravel save relation from input - php

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();

Related

How to add records to a pivot table in Laravel

I have a user, student and subject model and I want to register a student into many subjects. So I created a StudentRegistration controller and in my create view I show all the subjects that belong to the course of the current logged in user.
StudentRegistration.php create function
public function create()
{
$user_id = Auth::user()->id;
$student_id = Student::where('user_id', $user_id)->first();
$course = $student_id->course->id;
$subjects = Subject::where('course_id', $course)->get();
return view('student.create', compact('subjects'));
}
In the create template I show all the subjects as checkbox because a user can register for multiple subjects.
{!! Form::open(['method' => 'POST', 'action'=>'StudentRegistration#store', 'files'=>true]) !!}
#foreach($subjects as $subject)
<div class="label-box">
{!! Form::label('name', $subject->name) !!}
{!! Form::checkbox('subject_id[]', $subject->id, null, ['class'=>'form-control']) !!}
</div>
#endforeach
<div class="form-group">
{!! Form::submit('Create User', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
I have this in my Student.php for the many to many relationship:
public function subjects()
{
return $this->belongsToMany('App\Subject');
}
I created a pivot table named Student_Subject. So, during the store, how can I save all the selected subjects into pivot table (student_subject).
I tried using this:
public function store(Request $request)
{
$data = $request->except('_token');
$subject_count = count($data['subject_id']);
for($i=0; $i < $subject_count; $i++){
$student = Student::where('user_id', Auth::user()->id);
$student->subjects()->attach($data['subject_id'][$i]);
}
}
But I get the following error:
"Method Illuminate\Database\Query\Builder::subjects does not exist."
And how can I view all the course subjects which the student is not registered at?
I have this:
Route::get('/studentsubjects', function(){
$student_id = Student::where('user_id', Auth::id())->first();
$course = $student_id->course->id;
$subjects = $student_id->subjects;
echo 'Registered at' .'<br>';
foreach ($subjects as $registered) {
echo $registered->name .'<br>';
}
$unregistered = Subject::where('course_id', $course)->except($subjects);
});
And see this error:
"Method Illuminate\Database\Query\Builder::except does not exist."
$student = Student::where('user_id', Auth::user()->id);
is not enough to get the Student model, you're only getting the query object here.
In order to actually get the student, use the following:
$student = Student::where('user_id', Auth::user()->id)->first();
Even better if user_id is the primary key for your model Student:
$student = Student::find(Auth::user()->id);
As a side note, you can access directly the user ID from the Auth interface using Auth::id() instead of Auth::user()->id, resulting in:
$student = Student::find(Auth::id());

Laravel displaying the message for a specific person

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

Laravel 5.2 all data reset when update 1 single data

I have table dosen and I want to update data to "statusdosen" column.
I have url : ...admin/dosen/status
When I click save, the page redirect to ..admin/dosen and all data in that row has been reset (empty).
This is my view
{!! Form::model($value, ['route' => ['admin.dosen.update', $value->user_id], 'method' => 'PUT']) !!}
<br>
{!! Form::select('statusdosen', array('1' => 'Dikampus', '0' => 'Tidak Dikampus'), null, ['placeholder' => 'Pilih Status'], ['class' => 'form-control']) !!}
<br><br>
!! Form::button('<i class="fa fa-check-square-o"></i> Simpan', ['type' => 'submit', 'class' => 'btn btn-primary btn-sm'] ) !!}
{!! Form::close() !!}
Method :
public function status()
{
$dosen = Dosen::paginate(10);
return view('admin/dosen.status', compact('dosen'));
}
public function update($id)
{
$dosenUpdate = Request::only(['nipy', 'namadosen', 'alamatdosen', 'notelpdosen', 'tempatlahirdosen', 'tanggallahirdosen']);
$user = User::find($id);
$user->dosen()->update($dosenUpdate);
return redirect('admin/dosen')->with('message', 'Data berhasil diubah!');
}
what i want is after i click save it not redirect to other page. do i must create new update method data for 'statusdosen'?
I think you are looking for something along the line of this
public function update(Request $request, $id) {
// Make sure the value is true/1 or false/0
$this->validate($request, ['statusDosen' => 'boolean']);
// Retrieve only the status
$statusDosen = $request->get('statusDosen');
// Update user->dosen()
$user = User::find($id);
$user->dosen()->update($statusDosen);
// Redirect back to the page you came from with your message
return redirect()->back()->with('message', 'Data berhasil diubah!');
}
Ok that explains evreything
$user = User::find($id);
Actually this is same as
Update
dosen
Set
Columnname1=$data, Columnnam2=data2
Where
user_id = $id
This means all rows with this user_id will be updated.
You should be doing like below
public function update($id) {
$dosenUpdate = Request::only(['nipy', 'namadosen', 'alamatdosen', 'notelpdosen', 'tempatlahirdosen', 'tanggallahirdosen']);
//$user= User::find($id); $user->dosen()->update($dosenUpdate);
$dosen = dosen::find($id); // parameter $id must be id of the dosen you want to update
$dosen->update(dosenUpdate);
return back()->with('message', 'Data berhasil diubah!');
}
The return back() will take you back to the previous page but all input value will not be there as the page is being reloaded.
If you do want to keep the data you've two ways
Use return back()->withInput() and store the data to the corresponding input using old.
Use AJAX, and return a response as json.
Eg:
return response()->json(['message'=>'Data berhasil diubah!');

Laravel 5 form request validation returning forbidden error

I am trying to use Laravel 5.1's form request validation, to authorize if the request is from the owner. The validation is used when the user is trying to update part of the table clinics through the show.blade.php.
My set up so far:
routes.php:
Route::post('clinic/{id}',
array('as' => 'postUpdateAddress', 'uses' => 'ClinicController#postUpdateAddress'));
ClinicController.php:
public function postUpdateAddress($id,
\App\Http\Requests\UpdateClinicAddressFormRequest $request)
{
$clinic = Clinic::find($id);
$clinic->save();
return Redirect::route('clinic.index');
}
UpdateClinicAddressFormRequest.php:
public function authorize()
{
$clinicId = $this->route('postUpdateAddress');
return Clinic::where('id', $clinicId)
->where('user_id', Auth::id())
->exists();
}
Show.blade.php
{!! Form::open(array('route' => array('postUpdateAddress', $clinic->id), 'role'=>'form')) !!}
{!! Form::close() !!}
If I dd($clinicId) within the authorize function, it returns null, so I think that's where the problem lies!
Any help why on submit it's saying 'forbidden' would be hugely appreciated.
You are getting Forbidden Error because authorize() method of form request is returning false:
The issue is this: $clinicId = $this->route('postUpdateAddress');
To access a route parameter value in Form Requests you could do this:
$clinicId = \Route::input('id'); //to get the value of {id}
so authorize() should look like this:
public function authorize()
{
$clinicId = \Route::input('id'); //or $this->route('id');
return Clinic::where('id', $clinicId)
->where('user_id', Auth::id())
->exists();
}
I add this owner confirmation to authorize() method in Request and work
public function authorize()
{
return \Auth::check();
}

Eloquent ORM - update and delete not working

I am working on CRUD for my first Laravel project. Displaying and showing items is working fine.
I tried to update the entry with Query to confirm that I can change values in the table and it worked:
DB::update("UPDATE seasons SET title = 'foo' WHERE ID = 1");
My Problem is that neither updating nor deleting entries will work.
<?php
class SeasonAdminController extends \BaseController
{
// WORKS
public function store()
{
$season = new Season;
$season->title = Input::get('title');
$season->save();
Session::flash('message', 'success!');
return Redirect::to('backend/season');
}
// NOT WORKING
public function update($id)
{
$season = Season::find($id);
$season->title = Input::get('title');
$season->save();
Session::flash('message', 'success!');
return Redirect::to('backend/season');
}
// NOT WORKING
public function destroy($id)
{
Season::destroy($id);
Session::flash('message', 'success!');
return Redirect::to('backend/season/');
}
}
My Route is the following:
Route::resource('backend/season', 'SeasonAdminController');
The form-tag from the edit page:
{{ Form::model($season, array('route' => array('backend.season.update', $season->ID), 'method' => 'PUT')) }}
The form for deleting an entry:
{{ Form::open(array('url' => 'backend/season/' . $value->ID, 'class' => 'pull-right')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Löschen', array('class' => 'btn btn-danger')) }}
{{ Form::close() }}
What am I missing here. I appreciate you help, thank you!
The error was that I had "ID" instead of "id" as a primary key in the database table. I am not quite sure why this should not work, but I guess it has to do with the default primary key from the Eloquent Model.
public function update($id){
$inputs = Input::only(array('title'));
if (!$id->update($inputs)) {
Session::flash('message', 'Error!');
}else{
Session::flash('message', 'success!');
}
return Redirect::to('backend/season');
}
public function destroy($id){
if($id){
if($id->delete()){
Session::flash('message', 'Success: Deleted!');
}else{
Session::flash('message', 'Error: Not Deleted!');
}
}
return Redirect::to('backend/season');
}
Try it out.
By the way, the $id is not the season id, can't use find($id) on it because it's an object.
Edit:
You should follow this tutorial
https://www.packtpub.com/books/content/laravel-4-creating-simple-crud-application-hours
Because you do not yet understand how to use models in routes.
Take special attention on how forms are built.
Check your model
class Session extends Model{
protected $table = 'session '; //DB table name
protected $primaryKey = 'Id'; //Primary key Name... some time ORM cant identify the primary key
}

Categories