get id from url and passing into form in laravel 5 - laravel

i defined a route as
Route::get('roundtables/{name}/tags/store',['as'=>'tags.store','uses'=>'TagController#store','middleware'=>['owner','auth']]);
In my view, i have a form in this url
http://localhost:8000/roundtables/1/tags
<div class="col-md-3">
<div class="well">
{!! Form::open(['route'=>'tags.store','method'=>'GET']) !!}
<h2>New Tags</h2>
{{ Form::label('name','Name') }}
{{ Form::text('name',null,['class'=>'form-control']) }}
{{Form::submit('Create New Tag',['class'=>'btn btn-primary btn-block btn-h1-spacing'])}}
</div>
</div>
My problem is, how to get the id from url which is id '1' and passing into the form when user clicked submit.
My controller
public function store(Request $request,$name)
{
$this->validate($request,array('name'=>'required|max:255'));
$tag=new Tag;
$tag->name=$request->name;
$tag->roundtable_id=$name;
$tag->save();
Session::flash('success','New Tag was successfully added');
return redirect()->route('tags.index');
}

When you're using custom routes for CRUD, avoid using standard RESTful method and route names. Before building the form, you need to pass this variable to the view:
public function createTag($name)
{
....
return view('form', compact('name'));
}
Define your route as:
Route::get('roundtables/{name}/tags/storeTag',['as'=>'tags.storeTag','uses'=>'TagController#storeTag','middleware'=>['owner','auth']]);
Then pass variable to from the form:
{!! Form::open(['route' => ['tags.storeTag', $name], 'method'=>'GET']) !!}
And get it in the controller:
public function storeTag(Request $request, $name)
{
echo $name;

You get the wildcard value by using request() helper method easily.
{{request()->route('name')}}

In your TagController
public function index($name)
{
$tags= Tag::where($name)->first();
// add name parameter to return
return view('tags.index')->withTags($tags)->withName($name);
}
And in your view
<div class="col-md-3">
<div class="well">
//edit this form tag
{!! Form::open(['route'=>['tags.store',$name],'method'=>'GET']) !!}
<h2>New Tags</h2>
{{ Form::label('name','Name') }}
{{ Form::text('name',null,['class'=>'form-control']) }}
{{Form::submit('Create New Tag',['class'=>'btn btn-primary btn-block btn-h1-spacing'])}}
</div>
</div>
And in your TagController#store
public function store(Request $request,$name){
echo $name;
}

This should work.
Request::segment(2)
Or pass it from controller:
public function index($name)
{
$tags= Tag::where($name)->first();
return view('tags.index')->withTags($tags)->with('name', $name);
}
Then just pass it into the form:
{!! Form::open(['route'=>['tags.store', $name],'method'=>'GET']) !!}

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 to insert data with logged in user id? Laravel-6

I want to submit data to bidding table with logged in user id and auction id from product show method.
This is how my tables are in relation.
Is it good to use ProductController or should I create another controller for bidding table?
Product show blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="my-3 border">
<div class="row">
<div class="col-md-5">
<img src="/storage/images/{{$product->image}}" alt="" style="width: 100%;">
</div>
<div class="col-md-7">
<h2>{{$product->name}}</h2>
<p>{{$product->description}}</p>
<span>Category: {{$product->category->name}}</span><br>
<span class="text-right">Auction Ends: {{$product->auction->deadline}}</span>
<div class="price">Initial Price: {{$product->price}}</div>
{!! Form::open(['action' => 'BiddingsController#create', 'method' => 'POST', 'enctype' => 'multipart/form-data']) !!}
<div class="form-inline">
{{Form::number('bidamount', '',['class' => 'form-control mr-1', 'placeholder' => 'Place your bid'])}}
{{Form::submit('Place Bid', ['class' => 'btn btn-primary'])}}
</div>
{!! Form::close() !!}
#endsection
Bidding controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Bidding;
class BiddingsController extends Controller
{
public function index()
{
$biddings = Bidding::all();
return view('products.show' ,compact('biddings', $biddings));
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show(Bidding $bidding)
{
//
}
}
In a Laravel 6 app, you can get the Logged in user using the auth() helper.
$authUser = auth()->user();
Doc: https://laravel.com/docs/6.x/helpers#method-auth
Cordially
You can check anytime your logged details by Auth!
Everywhere and from anywhere you can use Auth::user()->id;
example:
for getting logged user id in controller check by!
dd(Auth::user()->id);
If needed just use Illuminate\Support\Facades\Auth in the very beginning of controller.

Laravel post error

I'm getting the following error message when trying to update user data:
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
I'm logging the user in, then want to give them the option to change their preferences. The form displays fine in the view but won't post.
Here are my routes:
Route::prefix('admin')->group(function(){
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminsController#index')->name('admin.dashboard');
Route::post('/', 'AdminsController#update')->name('admin.dashboard.update');
Route::get('/logout', 'Auth\AdminLoginController#logout')->name('admin.logout');
Here's the Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Admin;
use Auth;
class AdminsController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth:admin');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$id = Auth::user()->id;
$admin = Admin::find($id);
return view('admin')->with('admin',$admin);
}
public function update(Request $request, $id)
{
$this-> validate($request, [
'target_sector' => 'required|max:255',
'target_skillsets' => 'required|max:255',
'target_companies'=> 'required|max:255',
'target_locations'=> 'required|max:255',
]);
//Create Post
$id = Auth::user()->id;
$admin = Admin::find($id);
$admin->target_sector = $request->input('target_sector');
$admin->target_skillsets = $request->input('target_skillsets');
$admin->target_companies = $request->input('target_companies');
$admin->target_locations = $request->input('target_locations');
$admin->save();
return redirect('/admin')->with('success', 'Preferences Updated', 'admin',$admin);
}
}
And here is the view:
#include('includes.nav_login')
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row mt-4">
<div class="col-md-10 offset-md-1">
<div class="card">
<div class="card-header">Admin Dashboard</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
#endif
You are logged in as ADMIN!
</div>
<div class="card-header">Update Vacancy Preferences</div>
<div class="card-body">
{!! Form::open(['action' => ['AdminsController#update', $admin], 'method' => 'POST']) !!}
<div class="form-group">
{{Form::label('companies', 'Companies')}}
{{Form::text('companies', $admin->target_companies,['class'=>'form-control', 'placeholder'=>'Target Companies'])}}
</div>
<div class="form-group">
{{Form::label('skillsets', 'Skillsets')}}
{{Form::text('skillsets', $admin->target_skillsets,['class'=>'form-control', 'placeholder'=>'Skillsets'])}}
</div>
<div class="form-group">
{{Form::label('sector', 'Sector')}}
{{Form::text('sector', $admin->target_sector,['class'=>'form-control', 'placeholder'=>'Sector'])}}
</div>
<div class="form-group">
{{Form::label('locations', 'Locations')}}
{{Form::text('locations', $admin->target_locations,['class'=>'form-control', 'placeholder'=>'Locations'])}}
</div>
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('Update',['class'=>'btn btn-primary'])}}
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
#endsection
Can anyone explain why this isn't working?
You should fix you route, because you are using put method for update, but on routes, you defined as post
Route::post('/', 'AdminsController#update')->name('admin.dashboard.update');
Therefore error occurs.
You should fix your route like this,
Route::put('/{id}', 'AdminsController#update')->name('admin.dashboard.update');
I hope this help you.
The error says MethodNotAllowed which means you are hitting a route with a different request method than it accepts
you open the form like this
{!! Form::open(['action' => ['AdminsController#update', $admin], 'method' => 'POST']) !!}
so till now the form method is POST
but then you spoof the method to be of type put
{{Form::hidden('_method', 'PUT')}}
so now the method becomes of type put not post
however your route expects the method to be post
Route::post('/', 'AdminsController#update')->name('admin.dashboard.update');
This is why you get method not allowed exception
you either change the method on your controller to be put instead of post or remove the method spoofing thing from inside your form
I mean this line
//remove this
{{Form::hidden('_method', 'PUT')}}
once you fix it you will have another error because you don't have csrf field in your form so just add this inside of your form
#csrf
Really appreciate both answers on here - thanks #Mohammad Instanboli and #webdevtr.
Webdevtr was right to advise this:
Route::put('/{id}', 'AdminsController#update')->name('admin.dashboard.update');
I also had to go back and fix the following which I thought would be useful to note if anyone else views this with a similar issue:
Firstly my AdminsController#update method needed the following changes:
I changed the public function update to take one less variable - ($id)
public function update(Request $request)
{
$this-> validate($request, [
'target_sector' => 'required|max:255',
'target_skillsets' => 'required|max:255',
'target_companies'=> 'required|max:255',
'target_locations'=> 'required|max:255',
]);
//Create Post
$id = Auth::user()->id;
$admin = Admin::find($id);
$admin->target_sector = $request->input('target_sector');
$admin->target_skillsets = $request->input('target_skillsets');
$admin->target_companies = $request->input('target_companies');
$admin->target_locations = $request->input('target_locations');
$admin->save();
return redirect('/admin')->with('success', 'Preferences Updated', 'admin',$admin);
}
Then I needed to make sure the $request->input('x') matched the input names in the form in my view - i.e:
<div class="form-group">
{{Form::label('target_sector', 'target_sector')}}
{{Form::text('target_sector', $admin->target_sector,['class'=>'form-control', 'placeholder'=>'Sector'])}}
</div>

How to Call/Display Foreach Loop after Login

I had problem on calling page inside Foreach Loop.Although It is Okay before I click Login, but when I'd try to login,only the html tag where loaded and foreach loop cannot... On my HomeController extends Controller
public function index()
{
return view('pages.welcome');
}
on where I call welcome page. and inside of it which is foreach loop.
<div class="row">
<div class="col-md-8">
#foreach ($posts as $post)
<div class="post">
<h3>{{ $post->title }}</h3>
<p>{{ substr($post->body, 0,300) }}
{{ strlen($post->body) > 300 ? "..." : " " }}</p>
Read More...
</div>
<hr>
#endforeach
</div>
</div>
And I think the problem is my route:
Route::get('/home', 'HomeController#index');
You haven't passed the $posts variable to the view.
Change
public function index()
{
return view('pages.welcome');
}
To something like this:
public function index()
{
$posts = \App\Post::all(); //Assuming your model is called "Post" in the App namespace
return view('pages.welcome', compact('posts'));
}
NOTE: compact('posts') is just a shortcut for ['posts'=>$posts]

Don't show the URL's parameters in Laravel 4.1

I have a CRUD for Users in Laravel 4.1
When the user want see his data, the url is: mydomain.com/public/users/3 (the show method).
How I can hide the id "3" in the url? So, if the number is visible, the user can see the data of other users (as 4,5 or others id)?
Thanks
In my filter.php I have:
Route::group(array('before' => 'auth'), function()
{
Route::resource('users', 'UserController');
});
Finally solved.
In UserController.php:
public function show()
{
//
$usuario = Auth::user();
// show the view and pass the nerd to it
return View::make('users.show')
->with('elusuario', $usuario);
}
In show.blade.php
#extends ("layout/layout")
#section ("principal")
<div class="form-group">
{{ Form::label('nombre', 'Nombre') }}
{{ Form::text('nombre',null, array('class' => 'form-control','placeholder'=>$elusuario->nombre,'disabled'=>'disabled')) }}
</div>
<div class="form-group">
{{ Form::label('email', 'Email') }}
{{ Form::email('email',null, array('class' => 'form-control','placeholder'=>$elusuario->email,'disabled'=>'disabled')) }}
</div>
<a class="btn btn-success" href="{{ URL::to('users/' . $elusuario->id . '/edit') }}">Modificar datos</a>
#stop
That solved the issue and the url don't show the id of user. Simply called as mydomain.com/public/users/perfil and has the data (id, name, etc) from session variable.

Resources