Trying to execute multiple queries on same function - php

I am trying to execute 2 queries at the same time on the same function on my application. This function on the controller registers a new house in the system and at the same time, its suppose to feed a field in the Users table that has been null, and this field will then be updated with the new id of the house i have just created. For some reason, the first query works fine but i have been struggling with the second. I believe my logical is fine, maybe the Laravel syntax is making me a bit confused. Can someone help me?
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\House;
use App\User;
class AdminHouseController extends Controller
{
public function index(){
}
public function create($role_id){
if($role_id == 1){
return view('admin.house.create');
}else{
return redirect('home');
}
}
public function store(Request $request){
House::create($request->all());
$house_admin = Auth::user()->id;
$house = House::where('house_admin', $house_admin)->first();
User::findOrFail($house_admin)->update(['house_id' => $house->id]);
return redirect('home');
}
public function show($id){
}
public function edit($id){
}
public function update(Request $request, $id){
}
public function destroy($id){
}
}
This is my form
//i believe the problem is not here, but anyway
#extends('layouts.app')
#section('content')
<p><b>Register your house</b></p>
{!! Form::open(['method'=>'post', 'action'=>'AdminHouseController#store']) !!}
{!! Form::text('house_address', null,['placeholder'=>'House Address']) !!}
<input type="hidden" name="house_admin" value="{{Auth::user()->id}}">
{!! Form::number('nflatmates', null, ['placeholder'=>'How many flatmates']) !!}
{!! Form::submit('Register', ['class'=>'ui-btn buttonDefault']) !!}
{!! Form::close() !!}
#stop
And finnaly, this my router web.php
//i also believe the problem is not here, but in my controller
use App\User;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/house/{role_id}', 'AdminHouseController#create')->name('house');
Route::post('store', [
'uses' => 'AdminHouseController#store'
]);

You need to add the house_id field to the $fillable array in the User model:
protected $fillable = ['house_id', 'other_fields'];
Also, you have two foreign keys instead of one which is redundant. You might want to keep only house_admin foreign key.

Related

Cant store information on DB from Laravel form

I have this application using Laravel and im trying to register some information from the Form Class to my DB through the store method in the controller, but for some reason it throws me some error. I cant even print the request coming from the form, as usual. Can someone point me a possible mistake tht i am making? I am new to Laravel
This is my form on a view called create.blade.php
#extends('layouts.app')
#section('content')
<p><b>Register your house</b></p>
{!! Form::open(['method'=>'post', 'action'=>'AdminHouseController#store']) !!}
{!! Form::text('house_address', null,['placeholder'=>'House Address']) !!}
<input type="hidden" name="house_admin" value="{{Auth::user()->id}}">
{!! Form::number('nflatmates', null, ['placeholder'=>'How many flatmates']) !!}
{!! Form::submit('Register', ['class'=>'ui-btn buttonDefault']) !!}
{!! Form::close() !!}
#stop
This is my controller AdminHouseController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\House;
use App\User;
class AdminHouseController extends Controller
{
public function index(){
}
public function create($role_id){
if($role_id == 1){
return view('admin.house.create');
}else{
return redirect('home');
}
}
public function store(Request $request){
House::create($request->all());
return redirect('home');
}
public function show($id){
}
public function edit($id){
}
public function update(Request $request, $id){
}
public function destroy($id){
}
}
And this is my router file web.php
use App\User;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/house/{role_id}', 'AdminHouseController#create')->name('house');
Route::post('store', [
'uses' => 'AdminHouseController#store'
]);
you might be missing the {{ csrf_field() }} in the form this used to protect the form from tampering

Laravel route throws NotFoundHttpException

I'm looking for some help. I've searched on other topics, and saw what is the problem approximatively, but didn't succeed to fix it on my code.
Now the question is: I have NotFoundHttpException when i try to submit an update on my code.
Here is the Controller and my function update
<?php
namespace App\Http\Controllers;
use Request;
use App\Http\Requests;
use App\T_collaborateurs_table;
class testing extends Controller
{
public function index()
{
$user = T_collaborateurs_table::all();
return view ("read", compact("user"));
}
public function create()
{
return view("create");
}
public function store(Request $Request)
{
T_collaborateurs_table::create(Request::all());
return redirect("index");
}
public function show($id)
{
$user=T_collaborateurs_table::find($id);
return view("show", compact("user"));
}
public function edit($id)
{
$user=T_collaborateurs_table::find($id);
return view("update", compact("user"));
}
public function update(Request $Request, $id)
{
$user = T_collaborateurs_table::find($id);
$user->update(Request::all());
return redirect("index");
}
}
Now the routes
Route::get("create", "testing#create");
Route::post("store", "testing#store");
Route::get("index", "testing#index");
Route::get("show/{id}", "testing#show");
Route::get("edit/{id}", "testing#edit");
Route::patch("update/{id}", "testing#update");
And now the view update.blade.php
<body>
{{Form::model($user, ['method'=>'patch', 'action'=>['testing#update',$user->id]])}}
{{Form::label('Id_TCa', 'ID')}}
{{Form::text('Id_TCa')}}
{{Form::label('Collaborateur_TCa', 'collab')}}
{{Form::text('Collaborateur_TCa')}}
{{Form::label('Responsable_TCa', 'resp')}}
{{Form::text('Responsable_TCa')}}
{{Form::submit("update")}}
{{Form::close()}}
</body>
Here the route:list
I'm sorry if my words are not very understable...
Thank you all for your time.
{{Form::model($user, ['method'=>'PATCH', 'action'=> ['testing#update',$user->id]])}}
Or try to use 'route' instead of 'action',to use 'route' you just need a little edit in your update route.
Route::patch("update/{id}", array('as' => 'task-update', 'uses'=>'testing#update'));
in your view:
{{Form::model($user, ['method'=>'PATCH', 'route'=>['task-update',$user->id]])}}
And please follow the convention of class naming. Your class name should be 'TestingController' or 'Testing'.
You could try method spoofing by adding
{{ method_field('PATCH') }}
in your form and change the form method to POST
{{ Form::model($user, ['method'=>'POST', 'action'=>['testing#update', $user->id]]) }}
add the id as an hidden field
{{ Form::hidden('id', $user->id) }}
access the id in the controller as
public function update(Request $Request)
{
$id = Input::get('id');
$user = T_collaborateurs_table::find($id);
$user->update(Request::all());
return redirect("index");
}
also need to modify your route accordingly
Route::patch("update", "testing#update");
Try using on function update:
return redirect()->route('index');

Passing id through an link href in Laravel

is it possible to pass id through an link href in Laravel and display that page like /projects/display/2.
I have this link:
<td>View</td>
It displays the id when hovering over the link as /projects/display/2. But whenever i click on the link i get an error message of:
Sorry, the page you are looking for could not be found.
I have a view setup called projects/display, plus routes and controller.
routes:
<?php
Route::group(['middleware' => ['web']], function (){
Route::get('/', 'PagesController#getIndex');
Route::get('/login', 'PagesController#getLogin');
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::get('/projects/display', 'ProjectsController#getDisplay');
Route::resource('projects', 'ProjectsController');
});
Controller:
<?php
namespace App\Http\Controllers;
use App\project;
use App\Http\Requests;
use Illuminate\Http\Request;
use Session;
class ProjectsController extends Controller
{
public function index()
{
}
public function create()
{
return view('projects.create');
}
public function store(Request $request)
{
$this->validate($request, array(
'name' => 'required|max:200',
'description' => 'required'
));
$project = new project;
$project->name = $request->name;
$project->description = $request->description;
$project->save();
Session::flash('success', 'The project was successfully created!');
return redirect()->route('projects.show', $project->id);
}
public function show()
{
$project = Project::all();
return view('projects.show')->withProject($project);
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function getDisplay($id){
$project = Project::find($id);
return view('projects/display')->withProject($project);
}
}
You need to change your route to:
Route::get('/projects/display/{id}', 'ProjectsController#getDisplay');
And then generate URL with:
{{ url('projects/display/'.$projects->id) }}
If you write route like below,
Route::get('/projects/display/{projectId}', 'ProjectsController#getDisplay')->name('displayProject');
You can use the name 'displayProject' in the href and pass the id as Array :
<td>View</td>
What you are looking for is a parameterized route. Read more about them here:
https://laravel.com/docs/5.3/routing#required-parameters
I found a better solution:
In your blade file do like this
<a href="{{route('displayProject',"$id")}}">
View
</a>
with this route , in route file
Route::get('/projects/display/{id}', 'ProjectsController#getDisplay');
$id is sent form your controller with compact
return view('viewPage', compact('id'));

Laravel 5.1 - Showing Comments on Specific Page

Edit3: Could a reason be because both controllers are leading to the same page?
Edit2: Still not working after the answers I got.
Edit: Error one is solved, now I'm getting:
Undefined variable: project (View:
/var/www/resources/views/pages/showProject.blade.php)
Can this be because both variables are leading to the same page? The projects variable was working perfectly before the comment system.
public function index()
{
$projects = Project::all();
return view('pages.projects', compact('projects'));
}
Project variable declare.
I'm trying to get my comments from my database to show on a specific 'project page' in the laravel 5 project I'm working on. The idea is that the user can add art projects and other users can comment on them, but whenever I try to visit the page I get
Undefined variable: comments (View:
/var/www/resources/views/pages/showProject.blade.php)
This is my controller
public function index()
{
$comments = Comment::all();
return view('pages.showProject', compact('comments'));
}
public function store()
{
$input = Request::all();
$comment = new Comment;
$comment->body = $input['body'];
$comment->project_id = $input['project_id'];
$comment->user_id = Auth::user()->id;
$comment->save();
return redirect('projects/'.$input['project_id']);
}
These are my routes
// add comment
Route::post('projects/{id}','CommentController#store');
// show comments
Route::post('projects/{id}','CommentController#index');
And my view
#if (Auth::check())
<article> <!--Add comment -->
<br/>
{!! Form::open() !!}
{!! form::text('body', null, ['class' => 'form-control']) !!}
<br/>
{!! Form::Submit('Post Comment', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::hidden('project_id', $project->id) !!}
{!! Form::close() !!}
<br/>
</article>
<article>
#foreach ($comments as $comment)
<article>
<p>Body: {{ $comment->body }}</p>
<p>Author: {{ $comment->user->name }}</p>
</article>
#endforeach
</article>
#else
<p>Please log in to comment</p>
#endif
The Model
class Comment extends Model
{
//comments table in database
protected $guarded = [];
// user who has commented
public function author()
{
return $this->belongsTo('App\User','user_id');
}
// returns post of any comment
public function post()
{
return $this->belongsTo('App\Project','project_id');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public $timestamps = false;
}
Is there any way I can solve this?
Thanks in advance
First, you need to make sure that you are aliasing your 'Comment' model in your controller. This is done with the use statement.
use App\Comment;
class CommentController extends Controller
{
public function index()
{
$comments = Comment::all();
return view('pages.showProject', compact('comments'));
}
}
Second, you will need to change your route for showing comments from a POST request to a GET request. At the moment you are making identical routes and furthermore GET is the correct request type for retrieving data.
Route::get('projects/{id}','CommentController#index');
Third, you are referencing a $project variable in your view, but never passing it in from the controller. That needs to reference something.
I think your relationship is wrong. Try this:
Comment model:
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
User model:
class User extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
}
In the view you can use:
#foreach($comments as $comment)
<p>{{ $comment->user->name }}</p>
#endforeach
I needed to empty the show in the commentsController and only use it for saving the comments. For showing them I made an extra function in my projectsController. It ended up being this;
public function show($id)
{
$project = Project::findOrFail($id)->load("User");
$input = Request::all();
//-----------------------DB-----------------------------//
$project_comments = DB::table('comments')
->select('body', 'name')
->where('project_id', '=', $id)
->join('users', 'users.id', '=', 'user_id')
->get();
//-----------------------DB-----------------------------//
return view('pages.showProject', ['project' => Project::findOrFail($id), 'comments' => $project_comments]);
}

passing variable from blade(view) to route or controller

I want to pass the selected item's $id to my controller for doing changing on it .
it's my index.blade.php (view)code
<table>
#foreach($posts as $p)
<tr>
<td>{{$p->title}}</td>
<td>{{substr($p->body,0,120).'[...]'}}</td>
<td>{{HTML::link('posts_show',' Preview',array($p->id))}}</td>
<td>{{HTML::link('posts_edit','Edit',array($p->id))}}</td>
<td>
{{Form::open(array('method'=>'DELETE','url'=>array('posts.delete',$p->id)))}}
{{Form::submit('Delete')}}
{{Form::close()}}
</td>
</tr>
#endforeach
</table>
but it doesnt pass $id to my controller's methods.
thanks for your time.
What you need to do is to set route parameter. Your route should be like that.
Route::get('post','postController#index');
Route::get('posts_create', function (){ return View::make('admin.newPost'); });
Route::get('posts_show/{id}','postController#show');
Route::get('posts_edit/{id}','postController#edit');
Route::post('posts_delete/{id}','postController#destroy');
If you want to use named route {{ Form::open(array('url' => route('posts.edit', $p->id))) }}, you need to set name like that.
Route::post('posts_edit/{id}', array('uses' => 'postController#edit',
'as' => 'posts.edit'));
You can check routing in laravel official documentation.
Edit
For now, your form in view look like that.
{{ Form::open(array('url' => route('posts.edit', $post->id), 'method' => 'POST')) }}
In route,
Route::post('posts_edit/{id}', array('uses' => 'postController#edit',
'as' => 'posts.edit'));
In PostController,
public function edit($id)
{
// do something
}
I hope it might be useful.
Looks like your route has a name posts.destroy, if that is the case you should use route instead of url as a parameter
{{Form::open(array('method'=>'DELETE','route'=>array('posts.destroy',$p->id)))}}
it's my route:
Route::get('post','postController#index');
Route::get('posts_create', function (){ return View::make('admin.newPost'); });
Route::get('posts_show','postController#show');
Route::get('posts_edit','postController#edit');
Route::post('posts_delete','postController#destroy');
it's my postController:
class postController extends BaseController{
public function show($id){
$post=Post::find($id);
$date=$post->persian_date;
return View::make('posts.show')->with('post',$post)->with('date',$date);
}
public function edit($id){
$post=Post::find($id);
if(is_null($post)){
return Redirect::route('posts.index');
}
return View::make('posts.edit')->with('post',$post);
}
public function update($id){
$input=array_except(Input::all(),'_method');
Post::find($id)->update($input);
return Redirect::route('posts.index');
}
public function destroy($id)
{
Post::find($id)->delete();
return Redirect::route('posts.index');
}

Categories