Laravel store request all better way - laravel

I have following code:
//Create Assignment
$customer['projects_id'] = $Project->id;
$customer['user_id'] = $customeruser['user_id'];
$customer['user_name'] = $SalesRepresentative->user_name;
$customer['user_role'] = "Admin";
ProjectUser::firstOrCreate($customer);
Is there a way to write this code cleaner and don't have 4 lines? Maybe one instead? Thanks. request has a lot more values.

If you are using a validating request class you can simply call ProjectUser::firstOrCreate($request->validated()); in that case, only validated variables are passed to store method.

Related

Construct routes(urls) with slugs separated by dash in laravel

I am about to make more SEO-friendly URLs on my page and want a pattern looking like this for my products:
www.example.com/product-category/a-pretty-long-seo-friendly-product-name-12
So what are we looking at here?
www.example.com/{slug1}/{slug2}-{id}
The only thing I will care about from the URL in my controller is the {id}. The rest two slugs are just of SEO purpose. So to my question. How can I get the 12 from a-pretty-long-seo-friendly-product-name-12?
I have tried www.mydomain.com/{slug}/{slug}-{id} and in my controller to try and get $id. Id does not work. I am not able to able to separate it from from a-pretty-long-seo-friendly-product-name. So in my controller no matter how I do I get {slug2} and {id} concatenated.
Coming from rails it is a piece of cake there but can't seem to figure out how to do that here in laravel.
EDIT:
I am sorry I formulated my question very unclear. I am looking for a way to do this in the routes file. Like in rails.
You're on the right track, but you can't really logically separate /{slug}-{id} if you're using dash-separated strings. To handle this, you can simply explode the chunks and select the last one:
// routes/web.php
Route::get('/{primarySlug}/{secondarySlugAndId}', [ExampleController::class, 'example']);
// ExampleController.php
public function example($primarySlug, $secondarySlugAndId){
$parts = collect(explode('-', $secondarySlugAndId));
$id = $parts->last();
$secondarySlug = $parts->slice(0, -1)->implode('-');
... // Do anything else you need to do
}
Given the URL example.com/primary-slug/secondary-slug-99, you would have the following variables:
dd($primarySlug, $secondarySlug, $id);
// "primary-slug"
// "secondary-slug"
// "99"
The only case this wouldn't work for is if your id had a dash in it, but that's another layer of complexity that I hope you don't have to handle.
Route::get('/test/{slug1}/{slug2}','IndexController#index');
public function index($slug1, $slug2)
{
$id_slug = last(explode('-',$slug2));
$second_slug = str_replace('-'.$id_slug,'',$slug2);
dd($slug1, $second_slug,$id_slug);
}

Updating session vaules in CodeIgniter

Have a little problem, how to update single value in CI session.
I have
$data['jezik'] = $this->uri->segment(1);
$this->session->userdata('jezik',$data['jezik']);
$data['jezik']= $this->session->userdata('jezik');
But it does not change the value. Always the same!
Try:
$this->session->set_userdata('jezik',$data['jezik']);
You need to use set_userdata rather than userdata. There are two ways to do it. You can do it in a key/value type way
$this->session->set_userdata('jezik', $data['jezik']);
Or you can pass an array
$sessionData = array('jezik' => $data['jezik'])
$this->session->set_userdata('jezik',$data['jezik']);
You can read more about CodeIgniter sessions here
Like #Pattle said
$this->session->set_userdata('jezik', $data['jezik']);
Though I think he meant to pass in the array, like so:
$sessionData = array('jezik' => $data['jezik']);
$this->session->set_userdata($sessionData);

Codeigniter Route to accept dynamic values

I am trying to create a router which will take a dynamic value and forward it to the actual route. In normal case it would be like
$route['login'] = 'auth/login';
It is possible to catch a parameter before the login in the above parameter and pass it to as the first parameter to the actual route ? like
$route['^(.+)/login$'] = "$1/user/login";
Check out the documentation[docs]. There is a very easy way to do this.
$route['(:any)/login'] = '$1/auth/login';
Starx answer is correct but I wouldn't do that, as your first param will be your controller, and if you don't know what's in the dynamic value that's impossible to manage.
I would do :
$route['(:any)/login'] = 'user/login/$1';
This way, 'anything/login' would be redirected to your User controller, to the Login function with the parameter 'anything'.

Best practice in handling invalid parameter CodeIgniter

Let's say I have a method at Controller named
book($chapter,$page);
where $chapter and $page must be integer. To access the method, the URI will look like
book/chapter/page
For example,
book/1/1
If user try to access the URI without passing all parameter, or wrong parameter, like
book/1/
or
book/abcxyz/1
I can do some if else statements to handle, like
if(!empty($page)){
//process
}else{
//redirect
}
My question is, is there any best practice to handle those invalid parameters passed by user? My ultimate goal is to redirect to the main page whenever there is an invalid parameter? How can I achieve this?
Using the CodeIgniter routing in config/routes.php is pretty useful here, something like this:
$route['book/(:num)/(:num)'] = "book/$1/$2";
$route['book/(:any)'] = "error";
$route['book'] = "error";
Should catch everything. You can have pretty much any regular expressions in the routes, so can validate that the parameters are numeric, start with a lowercase letter, etc..
The best logic here seems to be adding the default values:
book($chapter = 1, $page = 1);
and then checking if they are numeric
So it automatically opens the 1st page of the 1st chapter if there are parameter missing or non-numeric.

codeigniter associative array in post

I normally name my db specific fields in my forms like this "objectname[columnname]", I tseems CI cant access these values using $this->input->post('objectname[columnname]'), what do I do? there is not a chance in hell im renaming 100+ form fields.. I am actually disliking CI, it really is getting in the way of progress by changing the de facto PHP norms...
And were you using $_POST['objectname[columnname]'] or $_POST['objectname']['columnname'] ?
Have you tried the equivalent for the latter
$obj = $this->input->post('objectname');
echo $obj['columnname'];
?
If it works, you can write you own helper to retreive that like post_val('objectname[columnname]').
I saw this post whilst looking for a similar issue, but worked out a CI way to do it, sorry if I'm resurrecting it, but it does appear fairly high on the Google results.
// Load the 'array' helper
$this->load->helper('array');
// Use the 'element' function to return an element from the array
echo element('ColumnName', $this->input->post('ObjectName'));
Hope this helps anyone who comes here in future.
HTML code:
<input type="text" value="" name="myPostArrayName[]">
<input type="text" value="" name="myPostArrayName[]">
Handling form with codeigniter:
$data = $this->input->post('myPostArrayName', TRUE);
You can access data in order like this
echo 'Value of the first element in the form array is '.$data[0];
echo 'Value of the second element in the form array is '.$data[1];
I think someone who has access to codeigniter documentation, had better to add a simple html post array handling example.
I seems I can rely on the $_POST var, but I thought this was reset?
You can cast the post array as an object and use method chaining to return sub-arrays (now properties) using PHP 5.3's method chaining all on one line.
Extend the input class by making a class called MY_Input and put the extended class in the application/core folder. CI 2.0 will automatically use the extended class with the MY_ prefix, and you can add methods to this new class. Extending the input class is cleaner than making helpers.
This method casts the post array, or a nested array (a sub array below the parent), as an object.
/* Cast an array from CI post as an object and return the object */
public function post_obj($key = null){
$post_return = $this->post($key);
if (false === $post_return)
return false;
return (object)$post_return;
}
Now I can retrieve nested values in one line of code using PHP 5.3's method chaining for objects.
$active = $this->input->post_obj('user')->active;
I just went with the $_POST['objectname']['colname'] option as i usually do even though this is probably not the CI way..

Resources