How to autofill fields in laravel? - php

I am trying to make the password of the user the same as the user id. What i don't want is to copy and paste the user id from the user id field into the password field. Instead, what i want to achieve is that as soon as i enter the user id, the same values get input into the password field. how can i achieve this? Below is my code:
Blade :
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-7">
<div class="card">
<div class="card-header">Add New User</div>
<div class="card-body">
{!! Form::open(['action'=>'AccountsController#store', 'method'=>'POST']) !!}
<div class="row form-group justify-content-center">
{{Form::label('name','Name',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::text('name','',['class'=>'form-control', 'placeholder'=>'Name'])}}
</div>
</div>
<div class="row form-group justify-content-center">
{{Form::label('email','Email',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::text('email','',['class'=>'form-control', 'placeholder'=>'Email'])}}
</div>
</div>
<div class="row form-group justify-content-center">
{{Form::label('userid','User I.D',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::text('userid','',['class'=>'form-control', 'placeholder'=>'User I.D'])}}
</div>
</div>
<div class="row form-group justify-content-center">
{{Form::label('password','Password',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::password('password',['class'=>'form-control', 'placeholder'=>'Password'])}}
</div>
</div>
<div class="row form-group justify-content-center">
{{Form::label('cpassword','Confirm Password',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::password('cpassword',['class'=>'form-control', 'placeholder'=>'Confrim Password'])}}
</div>
</div>
<div class="row form-group justify-content-center">
{{Form::submit('Submit',['class'=>'btn btn-primary'])}}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
</div>
#endsection
controller :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use App\Account;
use App\User;
class AccountsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
// $accounts = Account::all();
$accounts = User::all();
return view('accounts.create');
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('accounts.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request,[
'name'=>'required',
'email'=>'required',
'userid'=>'required',
'password'=>'required'
]);
// $account = new Account;
$account = new User;
$account->name = $request->input('name');
$account->email = $request->input('email');
$account->userid= $request->input('userid');
$account->password = bcrypt($request->input('password'));
$account->save();
return redirect('/accounts')->with('success', 'User has been successfully added!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
model :
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email','userid', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
database :
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('userid')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}

To achive such a dynamic operation you need JavaScript and I suggest to use JQuery for this. Here you can read more about it.
So first add JQuery to your project as described here.
Then use this code to achieve your goal:
<script type="text/javascript">
$(document).ready( function() {
$('#userid').on('change', function() {
$('#password').val($(this).val());
});
});
</script>
The code will listen for changes of the #userid element and then insert the value of it into the #password element.
The code needs to be on the same page as your form is.
If you're using jquery for further stuff I suggest to add those scripts by using the stacks mechanism of blade. It's described here. In my opinion this would be a bit better than entering the code directly in your view.

Related

storage’s server IP address could not be found

in Laravel 8 i was tried to show pdf file uploaded in storage folder,
and i got storage’s server IP address could not be found.
i want to uploade pdf file and show it on browser without download it
i used controlle function store to upload and show function to show pdf file
<?php
namespace App\Http\Controllers;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\App;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Pdf;
class PdfController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
protected function authenticated(Request $request, $user)
{
if ( $user->isAdmin() ) {// do your magic here
return redirect()->route('pdfs');
}
return redirect('/home');
}
public function __construct()
{
$this->middleware([
'auth:sanctum',
config('jetstream.auth_session'),
'verified'
])->except(['show']);
}
public function index()
{
$pdfs = Pdf::latest()->paginate(5);
return view('pdfs.index',compact('pdfs'))
->with('i', (request()->input('page', 1) - 1) * 5);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('pdfs.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'file' => 'required|mimes:pdf|max:2048',
]);
$fileModel = new pdf();
$pdf = $request->file;
$fileName = time() .'.pdf';
$filePath = $pdf->storeAs('uploads', $fileName, 'public');
$fileModel->name = $fileName;
$fileModel->file ='/storage/' . $filePath;
$fileModel->save();
return redirect()->route('pdfs.index')
->with('success','File has been uploaded.')
->with('pdf', $fileName);
}
/**
* Display the specified resource.
*
* #param \App\Models\Pdf $pdf
* #return \Illuminate\Http\Response
*/
public function show($ip)
{
$fileModel = Pdf::find($ip);
return view('pdfs.show', compact('fileModel'));
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Pdf $pdf
* #return \Illuminate\Http\Response
*/
public function edit(Pdf $pdf)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Pdf $pdf
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Pdf $pdf)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Pdf $pdf
* #return \Illuminate\Http\Response
*/
public function destroy(Pdf $pdf)
{
$pdf->delete();
return redirect()->route('pdfs.index')
->with('success','PDF deleted successfully');
}
}
this is my controller
#extends('pdfs.layout')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2> Show PDF</h2>
</div>
<div class="pull-right">
<a class="btn btn-primary" href="{{ route('pdfs.index') }}"> Back</a>
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
{{ $fileModel->name }}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<iframe src="/{{ $fileModel->file }}" frameborder="0"></iframe>
</div>
</div>
</div>
#endsection
and this is show.blade.php

Create view in one controller and store data in other controller laravel

I'm new to Laravel and I'm trying to store a form. I created the view with the House controller but now I want to store the data in the view with the Booking controller. But when I click the button nothing happens.
My question is if it is possible to make a view with one controller and store it with another controller or maybe there is an other solution.
I also want to use the id of the house to store. How do I get that in the other controller as well?
Web Route
<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [\App\Http\Controllers\HouseController::class, 'index']);
Route::get('house/{house}', [\App\Http\Controllers\HouseController::class, 'show']);
Route::post('house/{house}', [\App\Http\Controllers\BookingController::class, 'store']);
Route::get('rental', [\App\Http\Controllers\HouseController::class, 'getUserHouses']);
Route::get('rental/new', [\App\Http\Controllers\HouseController::class, 'create']);
Route::post('rental/new', [\App\Http\Controllers\HouseController::class, 'store']);
Route::get('rental/edit/{house}', [\App\Http\Controllers\HouseController::class, 'edit']);
Route::put('rental/edit/{house}', [\App\Http\Controllers\HouseController::class, 'update']);
Auth::routes();
Booking controller
<?php
namespace App\Http\Controllers;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class BookingController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$newBooking = Booking::create([
'user_id' => Auth::id(),
'house_id' => $request->id,
'begin' => $request->begin,
'end' => $request->end,
'status' => 0
]);
return redirect('/');
}
/**
* Display the specified resource.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function show(Booking $booking)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function edit(Booking $booking)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Booking $booking)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\Booking $booking
* #return \Illuminate\Http\Response
*/
public function destroy(Booking $booking)
{
//
}
}
House controller
<?php
namespace App\Http\Controllers;
use App\Models\house;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Helper\Imageable;
use DB;
class HouseController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$houses = House::all();
return view('/home', [
'houses' => $houses
]);
}
/**
* Display a listing of the houses the owner has
*
* #return \Illuminate\Http\Response
*/
public function getUserHouses()
{
$houses = DB::table('houses')
->where('user_id', '=', Auth::id())
->get();
return view('/rental/rental', [
'houses' => $houses
]);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('rental/new');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$path = Imageable::storeMedia($request);
$request->online === 'on' ? $online = 1 : $online = 0;
$newHouse = House::create([
'title' => $request->title,
'price_per_night' => $request->price,
'summary' => $request->summary,
'place' => $request->place,
'country' => $request->country,
'user_id' => Auth::id(),
'online' => $online,
'image' => $path,
]);
return redirect('rental');
}
/**
* Display the specified resource.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function show(house $house)
{
return view(
'/house',
[
'house' => $house
]
);
}
/**
* Show the form for editing the specified resource.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function edit(house $house)
{
return view(
'rental/edit',
[
'house' => $house
]
);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function update(Request $request, house $house)
{
$path = Imageable::storeMedia($request);
$request->online === 'on' ? $online = 1 : $online = 0;
$house->update([
'title' => $request->title,
'price_per_night' => $request->price,
'summary' => $request->summary,
'place' => $request->place,
'country' => $request->country,
'online' => $online,
'image' => $path,
]);
return redirect('rental/edit/' . $house->id);
}
/**
* Remove the specified resource from storage.
*
* #param \App\Models\house $house
* #return \Illuminate\Http\Response
*/
public function destroy(house $house)
{
//
}
}
View
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-12">
<h1 class="display-one ">{{ $house->title }}</h1>
<p class=".text-light">{{ $house->place }}, {{ $house->country }}</p>
</div>
</div>
<div class="row mt-5">
<div class="col-sm-6">
<img src="{{ asset("img/houses/$house->image") }}" alt="{{ $house->title }}" class="img-fluid" />
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="exampleFormControlSelect1">Kies een datum en reserveer direct</label>
<form method="POST" action="">
#csrf
<input type="date" name="begin">
<input type="date" name="end">
<div class="col-md-12 bg-light mt-3">
<button type="button" class="btn btn-warning ml-2">Vraag aan</button>
</div>
</form>
</div>
</div>
</div>
<div class="row mt-3">
<div class="col-sm-6">
<p class="display-one ">{{ $house->summary }}</p>
</div>
<div class="col-sm-6">
<h2 class="display-one ">Aangeboden door</h2>
<p>Prijs per nacht €{{ $house->price_per_night }}</p>
</div>
</div>
</div>
#endsection
First of all, nothing happens when you click the form submit button because it is currently type="button" and in order this button to play role of submission button it must be type="submit". You can do whatever you want with Laravel. If you want your form to hit another controller method you can simply specify that in your form tag. Like so:
Imagine this is a form inside a view that is rendered by HouseController
<form method="POST" action="{{ url('/save/from/booking/controller') }}">
// ....
</form>
And now on form submission inside a view that is rendered by HouseController, you will actually hit a route that is BookingController responsive for. And here is your route that is being hit by the form
Route::post('/save/from/booking/controller', [BookingController::class, 'store']);

How to make 'Create' button in a datatable to open modal to add new records to table?

I am using laravel 7 and yajra datatables and have managed to implement the datatable as a service. DataTatable As A Service. I am able to view data from mysql database on the datatable and would like to add more data to it. When i click the 'create' button defined on the datatable file, it redirects me to organizers/create which is another page. My requirement is that when i click the 'create' button, it should open a modal where i can capture data and add records to the database and show on table. Please assist.
Screenshot of the datatable
Web routes
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('broadcasts', 'admin\BroadcastController');
Route::resource('organizers', 'admin\OrganizerController');
Route::resource('profile', 'user\ProfileController');
Organizer Controller
namespace App\Http\Controllers\admin;
use App\DataTables\OrganizerDatatable;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redirect;
class OrganizerController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(OrganizerDatatable $datatable)
{
return $datatable->render('admin.organizers.organizers');
}
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
Organizer Datatable
namespace App\DataTables;
use App\Organizer;
use Illuminate\Database\Eloquent\Builder;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;
class OrganizerDatatable extends DataTable
{
/**
* Build DataTable class.
*
* #param mixed $query Results from query() method.
* #return \Yajra\DataTables\DataTableAbstract
*/
public function dataTable($query)
{
return datatables($query);
}
/**
* Get query source of dataTable.
*
* #return Builder
*/
public function query()
{
$organizers = Organizer::all();
return $this->applyScopes($organizers);
}
/**
* Optional method if you want to use html builder.
*
* #return \Yajra\DataTables\Html\Builder
*/
public function html()
{
return $this->builder()
->setTableId("organizers-table")
->columns($this->getColumns())
->minifiedAjax()
->dom('Bfrtip')
->orderBy(0, ['asc'])
->buttons($this->getButtons());
}
/**
* Get columns.
*
* #return array
*/
protected
function getColumns()
{
return [
Column::make('firstname'),
Column::make('lastname'),
Column::make('email'),
Column::make('gender'),
Column::make('phone'),
];
}
/**
* Get buttons.
*
* #return array
*/
protected
function getButtons(): array
{
return [
Button::make('create')->addClass('btn btn-sm'),
Button::make('reload')->addClass('btn btn-sm'),
Button::make('export')->addClass('btn btn-sm'),
Button::make('print')->addClass('btn btn-sm'),
Button::make('reset')->addClass('btn btn-sm'),
];
}
/**
* Get filename for export.
*
* #return string
*/
protected function filename()
{
return 'Organizer_' . date('YmdHis');
}
}
Where datatable is displayed
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<h6 class="font-weight-bolder">All Organizers</h6>
<hr style="width: 100%">
{!! $dataTable->table([], true) !!}
</div>
</div>
</div>
#push('scripts')
{!! $dataTable->scripts() !!}
#endpush
#endsection
you will add model design
<div class="modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary">Save changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
into your design page and call id of your model into create button.... Like This
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
Helping Link please Follow:
https://getbootstrap.com/docs/4.0/components/modal/

Returning select option value when editing in laravel

I am trying to edit a course. Now there is a drop down select field where you choose the program that course belongs to. I want to be able to return the program to the select field when i click on the edit button. Right now i am getting a Invalid argument supplied for foreach() error when i click on the edit button. How can i fix this and be able to get the value into the select field?
My code:
blade snippet
{!! Form::open(['action'=>['CoursesController#update', $course->id], 'method'=>'POST']) !!}
<div class="form-group row justify-content-center">
{{Form::label('program_code', 'Program Code')}}
<div class="col-md-4">
{!! Form::select('program_code', $course->program_code, ['class'=>'form-control']) !!}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('course_code', 'Course Code')}}
<div class="col-md-4">
{{Form::text('course_code',$course->course_code,['class'=>'form-control', 'placeholder'=>'Course Code'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('course_name', 'Course Name')}}
<div class="col-md-4">
{{Form::text('course_name',$course->course_name,['class'=>'form-control', 'placeholder'=>'Course Name'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::hidden('_method', 'PUT')}}
{{Form::submit('Add Program', ['class'=>'btn btn-success'])}}
</div>
{!! Form::close() !!}
controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Course;
use App\Program;
class CoursesController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$courses = Course::all();
return view('courses.index')->with('courses', $courses);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
// $programs = Program::all();
// return view('courses.create')->with('programs', $programs);
$programs = Program::all();
$select = [];
foreach($programs as $program){
$select[$program->program_code] = $program->program_name;
}
return view('courses.create', compact(['programs','select']));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'program_code' => 'required',
'course_code' => 'required',
'course_name' => 'required'
]);
$course = new Course;
$course->program_code = $request->input('program_code');
$course->course_code = $request->input('course_code');
$course->course_name = $request->input('course_name');
$course->save();
return redirect('/home/courses')->with('success', 'Course Successfully addded!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$course = Course::find($id);
return view('courses.edit')->with('course', $course);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'program_code' => 'required',
'course_code' => 'required',
'course_name' => 'required'
]);
$course = Course::find($id);
$course->program_code = $request->input('program_code');
$course->course_code = $request->input('course_code');
$course->course_name = $request->input('course_name');
$course->save();
return redirect('/home/courses')->with('success', 'Course Successfully updated!');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
For Forms select method parameter sequence is
name
list of items
default select value
extra parameters
You need to change code from
{!! Form::select('program_code', $course->program_code, ['class'=>'form-control']) !!}
to
{!! Form::select('program_code',["Option1","Option2","Option3",..], $course->program_code, ['class'=>'form-control']) !!}

Laravel: How to give each user different landing pages depending on their id

I am using the basic laravel auth login and registration code. I just added more functionality to the form. I am trying to make each user, as they log in, to be redirected to their own different pages depending on what account type they are. Right now each user is redirected to the home blade on login. how can i change this so they are redirected to each user's custom page? below is my code:
add user blade
#extends('layouts.app')
#section('content')
<div class="container" style="width:60%">
<div class="card">
<div class="card-header">Add New User</div>
<div class="card-body">
{!! Form::open(['action'=>'UserAccountsController#store', 'method'=>'POST']) !!}
#csrf
<div class="form-group row justify-content-center">
{{Form::label('acctyp', 'Account Type',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::select('acctyp',['Adm'=>'Admin','Rcd'=>'Records','Hod'=>'H.O.D','Tch'=>'Teacher','Std'=>'Student'],null,['placeholder'=>'Choose Account...','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('name', 'Name',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::text('name','',['placeholder'=>'Name','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('surname', 'Surname',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::text('surname','',['placeholder'=>'Surname','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('gender', 'Gender',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::select('gender',['F'=>'Female','M'=>'Male','O'=>'Other'],null,['placeholder'=>'Choose Gender...','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('dob', 'Date of Birth',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::date('dob','',['class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('email', 'E-mail Address',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::email('email','',['placeholder'=>'E-mail Address','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('userid', 'User I.D',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::text('userid','',['placeholder'=>'User I.D','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('password', 'Password',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::password('password',['placeholder'=>'Password','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::label('cpassword', 'Confirm Password',['class'=>'col-md-2'])}}
<div class="col-md-4">
{{Form::password('cpassword',['placeholder'=>'Confirm Password','class'=>'form-control'])}}
</div>
</div>
<div class="form-group row justify-content-center">
{{Form::submit('Add User',['class'=>'btn btn-success'])}}
</div>
{!! Form::close() !!}
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready( function() {
$('#userid').on('change', function() {
$('#password').val($(this).val());
$('#cpassword').val($(this).val());
});
});
</script>
#endsection
login controller
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
/*
|--------------------------------------------------------------------------
| Login Controller
|--------------------------------------------------------------------------
|
| This controller handles authenticating users for the application and
| redirecting them to your home screen. The controller uses a trait
| to conveniently provide its functionality to your applications.
|
*/
use AuthenticatesUsers;
/**
* Where to redirect users after login.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest')->except('logout');
}
}
add user conrtoller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
class UserAccountsController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$accounts = User::all();
return view('users.index')->with('accounts', $accounts);
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
return view('users.create');
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'acctyp'=>'required',
'name'=>'required',
'surname'=>'required',
'gender'=>'required',
'dob'=>'required',
'email'=>'required',
'userid'=>'required',
'password'=>'required',
]);
$account = new User;
$account->acctyp = $request->input('acctyp');
$account->name = $request->input('name');
$account->surname = $request->input('surname');
$account->gender = $request->input('gender');
$account->dob = $request->input('dob');
$account->email = $request->input('email');
$account->userid = $request->input('userid');
$account->password = bcrypt($request->input('password'));
$account->save();
return redirect('/users')->with('success', 'New user successfully added!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$account = User::find($id);
return view('users.show')->with('account', $account);
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
$account = User::find($id);
return view('users.edit')->with('account', $account);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'acctyp'=>'required',
'name'=>'required',
'surname'=>'required',
'gender'=>'required',
'dob'=>'required',
'email'=>'required',
'userid'=>'required',
'password'=>'required',
]);
$account = User::find($id);
$account->acctyp = $request->input('acctyp');
$account->name = $request->input('name');
$account->surname = $request->input('surname');
$account->gender = $request->input('gender');
$account->dob = $request->input('dob');
$account->email = $request->input('email');
$account->userid = $request->input('userid');
$account->password = bcrypt($request->input('password'));
$account->save();
return redirect('/users')->with('success', 'User successfully updated!');
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
$account = User::find($id);
$account->delete();
return redirect('/users')->with('success', 'User successfully removed!');
}
}
You should follow the below steps for that:
In LoginController.php
Override this method protected $redirectTo = '/home';
So you need to remove the above code and add following code:
public function redirectTo(){
$type = Auth::user()->acctyp;
switch ($type) {
case 'type1':
return '/YOUR PATH';
break;
case 'type2':
return '/YOUR PATH';
break;
default:
return '/YOUR PATH';
break;
}
}
Remember to include class Illuminate\Support\Facades\Auth; in LoginController.php
You can define a redirectTo method on your LoginController and return the path you want them redirected to:
protected function redirectTo()
{
// do your logic to decide where to go and return a path
$user = $this->guard()->user();
if ($user->acctyp == 'something') {
return route('something.dashboard');
}
...
}
When using the redirectTo method, the default setup will try to redirect them to a "intended" URL and fallback to what you return from redirectTo. (Intended would be where they were trying to reach before the auth middleware redirected them to the login page)
If you want full control over the response you can override the authenticated method on LoginController, which comes from the AuthenticatesUsers trait, to return the response you would like:
protected function authenticated(Request $request, $user)
{
// do your logic here and return a redirect
// to where you want them to go to
if ($user->acctyp == 'something') {
return redirect()->route('something.dashboard')
}
...
}

Categories