understanding how laravel interprets blade form url? - php

I have the below form in a larvel view:
<div id="admin">
<h1>Products Admin Panel</h1><hr>
<p>Here you can view, delete, and create new products.</p>
<h2>Products</h2><hr>
<!--admin/fileupload/create-->
{{ Form::open(array('url'=>'admin/products/create' , 'files'=>true)) }}
<p>
{{ Form::file('image') }}
</p>
{{ Form::submit('Create Product' , array('class'=>'secondary-cart-btn')) }}
{{ Form::close() }}
</div> <!-- end admin -->
I am new to laravel and basically just want to understand , in the URL when i specify 'url'=>'admin/products/create' , what is laravel going to look for ?
a modal called products ? or a controller called products ? and a method getCreate or postCreate inside it ? what is admin then , i want to understand how laravel interprets this blade form url , can anybody explain ?
I want somebody to explain to me how does laravel interpret blade form url ?

In laravel,you will specify which url to be processed by which controller and by which method inside that controller.This specify must be do in routes.php file that is located in projectname/app/Http/routes.php .
When you specify the 'url'=>'admin/products/create' you must define the route in routes.php .
Route can be define in different ways like:
Route::get('admin/products/create','ProductController#crete');
Here you can use get or post according to your request.
Another way you can do is
Route::get('admin/products/create',array(
'as'=> 'create-product',
'uses'=>'ProductController#create'
));
Now , you can do like this route('create-product'); instead of 'url'=>'admin/products/create' .
Another way by using Route group
Route::group(['prefix'=>'admin'],function(){
Route::group(['prefix'=>'products'],function(){
Route::get('/create',array(
'as'=>'create-product',
'uses'=> 'ProductController#create'
));
// Here you can define other route that have the url like /admin/products/*
});
});
Now you can do like route('create-product') or 'url'=>'admin/products/create' Advantage
For more info check the documentation Here

Related

Laravel - Conditional Route Name mapping / dynamic routes

I thought to write static routes like contact, imprint or "About Us" in the web.php as a one-liner. I saw this at Laravel Daily.
web.php
Route::get('/{page}', App\Http\Controllers\StaticPageController::class)
->name('page')
->where('page', 'about-us|imprint|contact');
It's nice but I'm getting problems with my navbar.
My Blade navbar has a dynamic part. The current menu item is highlighted. Very simple.
nav.blade.php
<x-nav-link :href="route('about-us')" :active="request()->routeIs('about-us')">
{{ __('About us') }}
</x-nav-link>
With the new one-liner, I then get the following error message:
Symfony\Component\Routing\Exception\RouteNotFoundException.
Route [about-us] not defined. (View: /project01/resources/views/includes/nav.blade.php)
Which is logical, because I no longer have the about-us route.
Actually, the route should be given a corresponding array mapping. But I don't know how. How can I solve the problem?
The solution for this problem will be:
<x-nav-link :href="route('page', ['page' => 'about-us'])" :active="request()->routeIs('about-us')">
{{ __('About us') }}
</x-nav-link>
Special Thanks for all good answears!
You have two options.
1- Change the routeIs() to is() and use the path, not the route name
<x-nav-link :href="route('page', ['page' => 'about-us'])" :active="request()->is('about-us/*')">
{{ __('About us') }}
</x-nav-link>
2- Switch back to 3 routes instead of the one liner. There is no gain in using the one liner. It is slower and harder to read (maintain)
You have assigned a name page to a given route with the required parameter named page. So, you must use the following code:
route('page', ['page' => 'about-us']);
https://laravel.com/docs/6.x/routing#named-routes
I think there is a misunderstanding.'about-us|imprint|contact' is the parameter restrictions.'page' is the route name.So this should work;
<x-nav-link :href="route('page','about-us')" :active="Request::url() == route('page','about-us')">
{{ __('About us') }}
</x-nav-link>

Laravel 5.1 - Pass parameter to Breadcrumbs

I use davejamesmiller Breadcrumbs package. I am wondering how to pass a parameter to a breadcrumb, something like an id.
In the docs (here) it says that is possible, but can't find the way to do it.
My goal es to do a breadcrumb like this: Dashboard \ User \ New Model. Where New Model its a form to add model data with some relationship with the user. Without the user_id param the link for User won't work.
Any idea?
You can pass global variable
\View::share ( 'variable2', $variable2 );
if render breadcrumbs in layout
or You need render breadcrumbs in `user.new_model.blade
#section('content')
{!! Breadcrumbs::render('page', $page) !!}
#stop`
my way
Create template
breadcrumbs.blade.php
with content
#if(!empty($breadcrumbs))
<ol class="breadcrumb">
<li>{!! link_to_route('main', 'Home') !!}</li>
#foreach($breadcrumbs as $bread)
#if(isset($bread['url']))
<li>{!! link_to($bread['url'], $bread['name']) !!}</li>
#else
<li>{!! $bread['name'] !!}</li>
#endif
#endforeach
</ol>
#endif
and connect it to layout
#include('breadcrumbs')
and in your action pass array of links
\View::share('breadcrumbs', [
['url' => route('collection.show', ['id'=>$data->collection, 'url'=>$data->collection]), 'name' => $data->collection->name],
['name' => $data->article]
]);
There is another way. As general, in each view just calling Breadcrumbs::render() should create the hierarchy of the breadcrumbs links depending on the routes defined in routes/breadcrumbs.php.
There are two essential points that you have keep in mind to go further with this solution:
The callback function that found in breadcrumbs.php routs definition is the place from which you should pass your parameters.
Giving correct name to your web route from routes/web.php which will be used later in routes/breadcrumbs.php
Checkout the following code snippets that demonstrates the above two points:
//Point1: routes/breadcrumbs.php
Breadcrumbs::register('job.edit', function($breadcrumbs, $job, $title)
{
$breadcrumbs->parent('job','job');
$breadcrumbs->push($title, route('job.edit', $job));
});
Breadcrumbs::register('job.edit.install', function($breadcrumbs, $job, $title)
{
$breadcrumbs->parent('job.edit',$job, $title);
$breadcrumbs->push('Job Install Equipments', route('job.edit.install','job'));
});
In the above code we passed $job and $title through the callback function.
//Point2 routes/web.php
Route::get('/job/edit/{job}', 'JobController#edit')->name('job.edit');
Route::get('/job/install-equipments/{job}', 'JobController#installEquipments')->name('job.edit.install');
We give a name to the route through the name method , Laravel 5.4, which allow us to define the routes correctly in Point1.
The last step, is what you have do in the view file. Here I will show you the last one regarding /job/install-equipments which should be rendered in the breadcrumb as the last element and its parent is job/edit with parameter job which handles the primary key id
//install.equipments.blade.php
#extends('layouts.main')
#section('content')
{!! Breadcrumbs::render('job.edit.install',$job->id, __('Edit').': '.$job->title) !!}
The above will render a breacrumbs look like:
Home / Job / Edit: title of
job / Job Install Equipment
The required parameters that handles breadcrumbs render are supplied un the above render method i.e through $job->id and __('Edit').': '.$job->title) , the last just adjusting the text and it could be done inside the callback function of breadcrumbs routes.

Populate form with Auth::user()

I'm trying to populate a form with my logged in user so I can edit some profile information.
I currently have this code (only trying to display the email first, will populate the form later once this works):
I made an editprofile.blade.php template with:
#extends('masterpage')
#section('content')
<h1> Edit Profile </h1>
{{ Form::model($user) }}
<div class="form-group">
{{ Form::label('email', 'E-mail') }}
{{ Form::Text('email', null, ['class' => 'form-control']) }}
</div>
{{ Form::close() }}
#stop
In myProfileController.php I have:
<?php namespace App\Http\Controllers;
use Auth;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Html\FormFacade;
use Illuminate\Html\HtmlFacade;
class ProfileController extends Controller {
public function show() {
$user = Auth::user();
return view('pages.editprofile')->withUser($user);
}
}
In my route I added:
Route::get('/profile/edit', 'ProfileController#show');
But when I try to load the page I get this:
I have two questions:
1: Why isn't there a form showing up with the data? As you can see the email is being loaded into the form but it displays it as text.
2. Once the data is loaded into a succesful form and the user has edited some of the data, how would I make update function to save the edited data?
I think that you are just outputting the raw data because probably you are using double brackets {{ }}.
As i remember i had a same thing when i migrated a site from laravel 4 to laravel 5. They changed the way blade output and echo the data. try to change double brackets {{ }} to this {{!! !!}} or this {{{ }}} i don't remember exactly which one it is.
Edit: about saving you can use controllers so when user post the data it goes to something like the same url just with post method, so it calls the update function inside controller.
For some functions where user should have full control over his profile like edit, update, delete, create i would use the examples from this http://laravel.com/docs/5.0/controllers#restful-resource-controllers take a look at restful controller

MethodNotAllowedHttpException on resource defined method Laravel-4

I created a very simple form so that I could use a submit button rather than a link to open up an edit users page. Using a link works perfectly, but the form button fails and yields a MethodNotAllowedHttpException even though the method ("edit") is perfectly defined in the UsersController resource and otherwise works fine.
Route:
Route::resource('users','UsersController');
UsersController:
public function edit($id)
{
$user = $this->user->find($id);
return View::make('users.edit')->with('user',$user);
}
show.blade.php:
<!-- This works fine: -->
{{ link_to_route('users.edit', ("Edit: " .$user->first_name." ".$user->last_name), $user->id) }}
<!-- This doesn't work, and yields the Method Not Allowed exception: -->
{{ Form::open(array('route' => array('users.edit',$user->id))) }}
{{ Form::submit('Edit User', array('class'=>'button')) }}
{{ Form::close() }}
Thanks.
When you do Form::open(), it defaults to using the post request method. But when you create a Route::resource(), the edit method takes a get request.
To make it work through the form, you'll need to open it with an additional parameter, like this:
{{ Form::open(array('route' => array('users.edit',$user->id),
'method' => 'get')) }}
You need to point to the update route, not edit.
{{ Form::open(array('route' => array('users.update', $user->id))) }}
The edit route is for displaying the view, while the update is for the put/patch request.
For more information about using the RESTful routes, I'd recommend checking out http://laravel.com/docs/controllers#resource-controllers

Laravel 4 - Multiple forms on same page?

I'm having some strange behavior with my forms in Laravel 4. I have a "settings" page with two forms, each (are supposed to) POST to a controller method, update the database and return back to the settings page. However, there seems to be an issue, either with the way my forms are working or my routes.
Here's how it is, simplified:
Settings page: (site.com/settings)
<div id="form-one" class="form-area">
{{ Form::open(array('action' => 'SettingController#editOption')) }}
{{ Form::text('optionvalue', 'Default')) }}
{{ Form::submit('Save Changes') }}
{{ Form::close() }}
</div>
<div id="form-two" class="form-area">
{{ Form::open(array('action' => 'SettingController#editPage')) }}
{{ Form::text('pagevalue', 'Default')) }}
{{ Form::submit('Save Changes') }}
{{ Form::close() }}
</div>
So basically, two seperate forms on the same page that post to two seperate methods in the same Controller - when the method is successful, it redirects them back to "settings". I won't post the methods, since tested them and they work, I believe the problem is in the routes file:
routes.php
// Checks if a session is active
Route::group(array('before' => 'require_login'), function()
{
Route::group(array('prefix' => 'settings'), function()
{
Route::get('/', 'SettingController#index');
Route::post('/', 'SettingController#editOption');
Route::post('/', 'SettingController#editPage');
});
});
Now I'm pretty sure it doesn't like the two POST routes being like that, however I cannot think of another way to do it, since the forms are on the same page. I get the error:
Unknown action [SettingController#editOption].
Since the option form comes first I guess. If I take the open form blade code out (for both), it loads the page - but obviously the form doesn't do anything.
Any help would be nice! Thanks in advance.
You can't add two same routes for different actions, because of they will be passed to first matched route and in your case to SettingController#editOption. Change your routes to :
Route::post('/option', 'SettingController#editOption');
Route::post('/page', 'SettingController#editPage');
Than in both actions you can redirect to '/': return Redirect::back(), and if error was occured:
if ($validation->fails())
{
return Redirect::to('/settings')->with_errors($validation);
}
My alternative solution for this is to create an hidden html input in each form and make the controller identify what for is submitted based in this field. So, yu can use just one route for both.

Categories