In my application, a user has the ability to remind another user about an event invitation. To do that, I need to pass both the IDs of the event, and of the user to be invited.
In my route file, I have:
Route::get('events/{id}/remind', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
In my view, I have:
{!!link_to_route('remindHelper', 'Remind User', $parameters = array($eventid = $event->id, $userid = $invitee->id) )!!}
In my controller, I have:
public function remindHelper($eventid, $userid)
{
$event = Events::findOrFail($eventid);
$user = User::findOrFail($userid);
$invitees = $this->user->friendsOfMine;
$invited = $event->helpers;
$groups = $this->user->groupOwner()->get();
return view('events.invite_groups', compact('event', 'invitees', 'invited', 'groups'));
}
However, when I hit that route, I receive the following error:
Missing argument 2 for App\Http\Controllers\EventsController::remindHelper()
I'm sure I have a formatting error in my view, but I've been unable to diagnose it. Is there a more efficient way to pass multiple arguments to a controller?
When you define this route:
Route::get('events/{id}/remind', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
You are saying that a single URI argument will be passed to the method.
Try passing the two arguments, like:
Route::get('events/{event}/remind/{user}', [
'as' => 'remindHelper', 'uses' => 'EventsController#remindHelper']);
View:
route('remindHelper',['event'=>$eventId,'user'=>$userId]);
Route :
Route::get('warden/building/{buildingId}/employee/{employeeId}',[
'uses'=>'WardenController#deleteWarden',
'as'=>'delete-warden'
]);
View :
Controller:
public function deleteWarden($buildingId,$employeeId){
$building = Building::find($buildingId);
$building->employees()->detach($employeeId);
return redirect('warden/assign/'.$buildingId)->with('message','Warden Detached successfully');
}
This is how you do it:
Click Here
Go to your controller and write code like following:
public function passData()
{
$comboCoder=['Bappy','Sanjid','Rana','Tuhin'];
$ffi=['Faisal','Sanjid','Babul','Quiyum','Tusar','Fahim'];
$classRoom=['Sanjid','Tamanna','Liza'];
return view('hyper.passData',compact('comboCoder','ffi','classRoom'));
}
/*
Again, in View part use:
(passData.blade.php)
*/
<u>Combocoder:</u>
#foreach($comboCoder as $c)
{{$c}}<br>
#endforeach
<u>FFI</u>
#foreach($ffi as $f)
{{$f}}<br>
#endforeach
<u>Class Room </u>
#foreach($classRoom as $cr)
{{$cr}}<br>
#endforeach
Route::get('/details/{id}/{id1}/{id2}', 'HomeController#SearchDetails');
//pass data like the below code
<a href="{{url("/details/{$orga_list->dcode}/{$orga_list->dname}/{$GroupHead}")}}"
target="_blank" > Details </a>
//controller write like the below code
public function SearchDetails($id, $searchtext,$grp_searchtext)
{
// get data like the below code
$data['searchtext'] = $searchtext;
$data['grp_searchtext'] = $grp_searchtext;
$data['id_is'] = $id;
}
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\BookController;
Route::controller(BookController::class)->group(function () {
Route::get('author/{author_name}/book/{title}', 'show')
->name('book.show');
});
Now update the controller like:
app/Http/Controllers/BookController.php
namespace App\Http\Controllers;
use App\Models\Book;
use App\Models\Author;
use Illuminate\Http\Request;
class BookController extends Controller
{
public function show(Request $request, Author $author, Book $book)
{
return view('show',[
'book' => $book->show($request)
]);
}
}
Now update the book model:
app\Models\Book.php
namespace App\Models;
use App\Common\HasPdf;
use App\Common\HasImage;
use Illuminate\Contracts\Database\Eloquent\Builder;
use Illuminate\Support\Facades\URL;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Book extends Model
{
use HasFactory;
protected $guarded = [];
public function author() : BelongsTo
{
return $this->belongsTo(Author::class);
}
public function url()
{
return URL::route('book.show', [
'author_name' => $this->author->author_name,
'title' => $this->title,
]);
}
}
<h3>{{ $item->title }}</h3>
Hope it can help you.
Related
I am trying to get exercise id to complete the table, how can I get the exercise ID, like I am getting it in Auth::user()->id
<?php
namespace App\Http\Controllers;
use App\Models\MyExercises;
use Illuminate\Http\Request;
use App\Models\Exercise;
use Illuminate\Support\Facades\Auth;
class MyExerciseController extends Controller
{
public function index()
{
$myexercises = MyExercises::paginate();
return view('exercises.myexercises', compact('myexercises'));
}
public function assign(Request $request)
{
$myexercises = MyExercises::create([
'description' =>$request->description,
'done' =>$request->done,
'user_id' => Auth::user()->id,
'exercises_id' =>(xxxxxx),
'place' =>$request->place,
'duration' =>$request->duration,
]);
return redirect()->route('myexercises.index');
I have tried doing it like this in the Controller, but right now I am a bit lost on how to proceed, thank you!
public function id()
{
$client = DB::table('My_exercises')
->where('id', '=', $request->get('id'))
->first();
}
I'm trying to pass my article data to the single page article named article.blade.php although all the data are recorded into the database but when I tried to return them in my view, nothing showed and the [ ] was empty. Nothing returned.
this is my articleController.php
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
public function single(Article $article)
{
return $article;
}
}
this is my model:
<?php
namespace App;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use Sluggable;
protected $guarded = [];
protected $casts = [
'images' => 'array'
];
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
public function path()
{
return "/articles/$this->slug";
}
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
and this is my Route
Route::get('/articles/{articleSlug}' , 'ArticleController#single');
Change your code to
class ArticleController extends Controller
{
public function single(Article $article)
{
return view('article', compact('article'));
}
}
change route to
Route::get('/articles/{article}' , 'ArticleController#single');
And model
public function getRouteKeyName()
{
return 'slug';
}
See docs https://laravel.com/docs/5.7/routing#route-model-binding
You might not be getting any data because you have not specified that you're using title_slug as the route key for model binding in your model.
Add this to your model class and it should give you the data
public function getRouteKeyName()
{
return 'slug';
}
Then you can return the data in json, view or other format.
Depending on what you try to archive, you need to either ...
return $article->toJson(); // or ->toArray();
.. for json response or ..
return view(..., ['article' => $article])
for passing a the article to a certain view
I just finishing my blog, using laravel, and I want to add a comment feature on it, but i got few errors like this, can anyone help me, please??,
sorry for my English, English is not my native language,
Thank you :)
(1/1) ErrorException
Undefined offset: 1
Here is my AdminBlog.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AdminBlog extends Model
{
protected $table = 'admin';
protected $fillable = ['title','text','images','slug'];
public function comment(){
return $this->hasMany('App\Comment');
}
}
Comment.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comment';
protected $fillable = ['name','email','text','post_id'];
public function post(){
return $this->belongsTo('App\AdminBlog');
}
}
BlogController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\AdminBlog;
use App\Comment;
class BlogController extends Controller
{
//Index
public function index(){
$post = AdminBlog::all();
return view('blog/index', compact('post'));
}
//Show
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
}
show.blade.php
<div class="col-md-12 post-comment-show">
#foreach($post->comment() as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
You should use:
<div class="col-md-12 post-comment-show">
#foreach($post->comment as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
Note that, you have used comment(). Also, you should use a plural name for a hasMany relationship, so comment should be comments.
Also, in your show method, you should use something like the following:
public function show($id)
{
$post = AdminBlog::with('comment')->findOrFail($id);
return view('blog/show', ['post' => $post]);
}
Try the following
$post->comment()->get()
or
$post->comment
when calling a relationship with ()it returns a instance of the query builder and allows you to filter the object. If you remove the call it without () it returns you a collection which is array accessible
Another suggestion if you have many comments you should name your relationship plural.
in this case:
public function comments(){
return $this->hasMany('App\Comment');
}
// Use it like this
$post->comments
You need to change your show function:
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
TO
public function show($id){
$post = AdminBlog::with('comment')->where('admin.id',$id)->get();
return view('blog/show', compact('post'));
}
Hope this work for you!
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'));
I have a groups table in my database and each group has a slug. I have the following routes defined last in my routes.php file so that if no other URL is matched the app checks whether the slug belongs to a group and shows the group page instead. There is also a form on the group page so the submission of this form needs to be handled as well.
Route::get('{slug}', ['as' => 'dynamic_route', function($slug){
$group = \App\Group::where('slug', $slug)->first();
if(!is_null($group)) {
$app = app();
$controller = $app->make('App\Http\Controllers\GroupsController');
return $controller->callAction('view', ['slug' => $group->slug]);
} else {
abort(404);
}
}]);
Route::post('{slug}', ['as' => 'dynamic_route_submit', function($slug){
$group = \App\Group::where('slug', $slug)->first();
if(!is_null($group)) {
$app = app();
$controller = $app->make('App\Http\Controllers\GroupsController');
return $controller->callAction('handle_register', [$group->slug]);
} else {
abort(404);
}
}]);
Here is my groups controller:
<?php namespace App\Http\Controllers;
use View;
use App\Group;
use App\Lifestyle_question;
use App\Http\Requests\User\RegisterStep1Request;
use App\Http\Requests\User\RegisterStep2Request;
use Breadcrumbs;
class GroupsController extends FrontendController {
public function __construct()
{
parent::__construct();
}
function view($slug)
{
$this->data['group'] = Group::where('slug', '=', $slug)->first();
$this->data['lifestyle_questions'] = Lifestyle_question::all();
Breadcrumbs::setCurrentRoute('dynamic_route', $this->data['group']);
return View::make('groups/view', $this->data);
}
function handle_register(RegisterStep1Request $request1, RegisterStep2Request $request2, $slug)
{
$this->data['group'] = Group::where('slug', '=', $slug)->first();
die("Validation passed");
}
}
The view method works fine however when I submit the form I get the following error message:
ErrorException in GroupsController.php line 27:
Argument 1 passed to App\Http\Controllers\GroupsController::handle_register() must be an instance of App\Http\Requests\User\RegisterStep1Request, string given
I know this has to do with the parameters that are being passed to the controller method from the route definition and so I tried the following in an attempt to sort it:
Route::post('{slug}', ['as' => 'dynamic_route_submit', function($slug){
$group = \App\Group::where('slug', $slug)->first();
if(!is_null($group)) {
$app = app();
$controller = $app->make('App\Http\Controllers\GroupsController');
return $controller->callAction('handle_register', [new \App\Http\Requests\User\RegisterStep1Request, new \App\Http\Requests\User\RegisterStep2Request, $group->slug]);
} else {
abort(404);
}
}]);
This fixed the issue except the requests just didn't get triggered. How can I call this method and ensure that the requests get triggered so that the validation is run?
Never use an anonymous function in the routing if you're going to call a controller inside of it. Declare your route like this:
Route::post('{slug}', ['as' => 'dynamic_route_submit', 'uses' => 'App\Http\Controllers\GroupsController#handle_register']);
Then in the controller handle whatever validation is necessary.
You could try moving your request validations out of the Request classes and into private controller actions:
UserController.php
/**
* Validates a Create User request
*/
protected function validateCreate()
{
$this->validate($this->request, [
'name' => 'required|max:255',
'email' => 'required|unique:users|max:255',
'account_types_id' => 'required|numeric',
]);
}
So do something similar with your code and call these validation methods from within your controller action:
UserController.php
/**
* #return \Illuminate\Http\RedirectResponse
* #throws CreateException
*/
public function create()
{
$this->validateCreate();
As an FYI you can access route parameters by name using request()->route()->getParameter('slug')
$slug = request()->route()->getParameter('slug');
$this->data['group'] = Group::where('slug', '=', $slug)->first();